当Axios请求被取消时,如何停止Laravel中的php脚本?

当Axios请求被取消时,如何停止Laravel中的php脚本?,php,laravel,axios,Php,Laravel,Axios,我正在使用Laravel、VueJs和axios进行实时搜索,因此每次用户键入新词时,之前的请求都将被取消。我的问题是,即使使用cancel token()取消上一个请求,php脚本仍在运行 问题:如果axios请求已被取消,如何停止php脚本 我的Vuejs代码 fetchData(query) { if(cancel != undefined) cancel(); // cancel the previous request axios.get("http

我正在使用Laravel、VueJs和axios进行实时搜索,因此每次用户键入新词时,之前的请求都将被取消。我的问题是,即使使用cancel token()取消上一个请求,php脚本仍在运行

问题:如果axios请求已被取消,如何停止php脚本

我的Vuejs代码

fetchData(query) {
    if(cancel != undefined)
        cancel();   // cancel the previous request
    axios.get("http://sample-link", {
            cancelToken: new CancelToken(function executor(c) {
                cancel = c;
            }),
            params: {
                query : query
            }
    }).then(response => {
        console.log(response);  
    }).catch(error => {console.log(error.message)})
}

...

class SearchController extends Controller {
    public function Search(Request $request)
    {
        $query = $request->input('query');
        $accounts = Accounts::search($query, null, true, true)->get();
        return response()->json($accounts);
    }
    ...
}

我的php代码

fetchData(query) {
    if(cancel != undefined)
        cancel();   // cancel the previous request
    axios.get("http://sample-link", {
            cancelToken: new CancelToken(function executor(c) {
                cancel = c;
            }),
            params: {
                query : query
            }
    }).then(response => {
        console.log(response);  
    }).catch(error => {console.log(error.message)})
}

...

class SearchController extends Controller {
    public function Search(Request $request)
    {
        $query = $request->input('query');
        $accounts = Accounts::search($query, null, true, true)->get();
        return response()->json($accounts);
    }
    ...
}


我不知道Axios取消是如何工作的,但是如果客户端断开HTTP会话(应该断开),您可以尝试使用该设置

其他有用的功能可以是:

:检查连接的当前状态

:检查连接是否已取消


我只想补充一点,您的函数似乎不是很密集,所以我不确定这样的检查有多有用。正如Tauqeer在评论中所建议的那样,在这些情况下,通常的方法是对javascript搜索函数应用去抖动,以便仅在用户完成键入时触发请求

示例使用:


现在,只要用户键入内容,您就可以调用
fetchData(query)
,只有当用户停止键入300毫秒时,它才会发送请求

您不能在调用服务器之前等待片刻吗?您可以使用setTimeout函数或lodash debounce函数来实现这一点。我还成功地添加了某种消息ID。对于发送的每一条消息,您将其递增一,后端也会使用该消息ID进行响应。也可以是当前时间戳,即您想要的时间戳。javascript客户机然后会丢弃它发出的旧请求的响应。