【问题标题】:How to stop php script in Laravel when Axios request is cancelled?取消 Axios 请求时如何在 Laravel 中停止 php 脚本?
【发布时间】:2020-09-13 01:54:07
【问题描述】:

我正在使用 Laravel、VueJs 和 axios 进行实时搜索,所以每次用户输入一个新单词时,之前的请求都会被取消。我的问题是,即使我使用取消令牌 (https://github.com/axios/axios#cancellation) 取消了上一个请求,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)})
}

...

我的 php 代码


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);
    }
    ...
}

【问题讨论】:

  • 您不能在调用服务器之前稍等片刻吗?您可以使用 setTimeout 函数来实现这一点,也可以使用 lodash debounce 函数。

标签: php laravel axios


【解决方案1】:

我不知道 Axios 取消的具体工作原理,但如果客户端断开 HTTP 会话(应该如此),您可以尝试使用 ignore_user_abort 设置。

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

其他有用的功能可能是:

connection_status:检查当前连接状态

connection_aborted: 检查连接是否被取消


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

一个使用lodash的例子:


const search = (query) => {
    .. your axios request ...
}

const fetchData = _.debounce(search, 300) 

现在您只需在用户输入内容时调用fetchData(query),它只会在用户停止输入 300 毫秒时发送请求

【讨论】:

  • 我也成功添加了某种消息 ID。对于发送的每条消息,您将其加一,并且后端也使用该消息 ID 进行响应。也可以是您想要的当前时间戳。然后,javascript 客户端会丢弃它发出的旧请求的响应。
猜你喜欢
  • 1970-01-01
  • 2016-11-14
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
  • 2020-07-15
相关资源
最近更新 更多