You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

中止AJAX请求后页面仍卡顿,需优化ChatGPT请求终止逻辑

请求终止功能实现方案

问题说明

需要实现请求终止功能,允许用户随时离开页面。当前遇到的问题是:前端调用xhr.abort()中止请求后,用户仍会被卡在页面,直到后端完成ChatGPT请求的执行。

问题根源

前端的xhr.abort()仅会断开浏览器与服务器的HTTP连接,但后端的PHP进程会继续执行OpenAI的同步请求,直到拿到返回结果才会终止。这导致服务器资源被占用,且用户页面无法及时响应跳转操作。

前端优化代码

var xhr = $.post(url, data, (response) => {
    if (response.success) {
        // 原有处理逻辑
    }
});

$('a').click(function(e) {
    e.preventDefault();
    // 中止请求
    if (xhr) {
        xhr.abort();
    }
    // 强制跳转页面
    window.location.href = $(this).attr('href');
});
  • 增加e.preventDefault()阻止默认跳转逻辑,先手动中止请求再执行跳转,确保页面能立即响应
  • 增加xhr存在性判断,避免未发起请求时的报错

后端处理方案

核心是让PHP检测客户端连接状态,一旦发现连接断开,立即终止OpenAI请求。需要使用OpenAI的流式API实现中途中断:

ignore_user_abort(false); // 允许客户端断开后终止脚本
set_time_limit(0); // 根据需求设置超时时间,0表示无限制

$open_ai_key = get_field('openai_api_key', 'options');
$open_ai = new Orhanerday\OpenAi\OpenAi($open_ai_key);

$full_response = '';
$stream_callback = function($curl_info, $data) use (&$full_response) {
    // 检测客户端是否已经断开连接
    if (connection_aborted()) {
        // 返回-1终止curl请求
        return -1;
    }

    // 处理流式返回的数据
    $chunk = json_decode($data, true);
    if (isset($chunk['choices'][0]['delta']['content'])) {
        $full_response .= $chunk['choices'][0]['delta']['content'];
    }
    return strlen($data);
};

// 调用流式ChatGPT API
$open_ai->chat([
    'model'             => 'gpt-4',
    'messages'          => [
        [
            "role" => "user",
            "content" => $prompt_with_direction
        ],
    ],
    'temperature'       => 0,
    'top_p'             => 1,
    'max_tokens'        => 1024,
    'frequency_penalty' => 0,
    'presence_penalty'  => 0,
    'stream'            => true, // 开启流式响应
], $stream_callback);

// 仅在请求正常完成时返回结果
if (!connection_aborted()) {
    wp_send_json_success($full_response);
}
  • 开启stream: true使用流式API,分块接收数据的同时检测连接状态
  • 通过connection_aborted()判断客户端是否断开,一旦断开立即终止curl请求
  • 收集所有流式数据,在请求正常完成时返回完整结果

内容的提问来源于stack exchange,提问作者B23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 16:47:34