首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将php立即发送到ajax?

如何将php立即发送到ajax?
EN

Stack Overflow用户
提问于 2018-08-21 05:14:03
回答 2查看 0关注 0票数 0

我使用jquery的ajax来调用php api:

代码语言:javascript
复制
$.ajax({
            type:"POST",
            dataType:"json",
            data:{type:type,fid:fid,model:'star'},
            url:'Recommend/Star/mark',
            success:function (data) {
                //do something
            },
        ...
      });

Recommend/Star/mark方法中的PHP代码:

代码语言:javascript
复制
    error_reporting(0);
    set_time_limit(0);
    ob_implicit_flush(true);
    ob_end_clean();

    ob_start ();
    echo json_encode($boolMark);
    ob_flush();
    flush();

    sleep(3);
    $this->afterMark($uid, $fid);

我想立即向ajax发送php echo结果,但我的代码不起作用。

如何让php立即将结果发送到ajax,并继续执行剩余的代码?

EN

回答 2

Stack Overflow用户

发布于 2018-08-21 13:41:23

代码语言:txt
复制
 ....
 echo json_encode($boolMark . "<br>\n");
 // get the size of the output
 $size = ob_get_length();
 // send headers to tell the browser to close the connection
 header("Content-Length: $size");
 header('Connection: close');
 ob_end_flush();
 ob_flush();
 flush();
 /******** background process starts here ********/

 ignore_user_abort(true);

 /******** background process ********/
 set_time_limit(0); //no time limit

 /******** Rest of your code starts here ********/
票数 0
EN

Stack Overflow用户

发布于 2018-08-21 15:01:05

你希望你的代码在发送响应后在“后台”运行,为此你需要这样做:

代码语言:javascript
复制
// Destroy the current buffer (Just in case...)
ob_clean();
// Start a new buffer
ob_start();

// Send your response.
echo json_encode($boolMark);

// Disable compression (in case content length is compressed).
header("Content-Encoding: none");

// Set the content length of the response.
header("Content-Length: ".ob_get_length());

// Close the connection.
header("Connection: close");

// Flush all output.
ob_end_flush();
ob_flush();
flush();

这会发送完整的标头并关闭连接,否则你的连接将保持活动状态,浏览器将等待php脚本终止其执行。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100002323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档