我有一个简单的 jquery 函数,它将 post 请求发送到 PHP 文件,如下所示:
$.post('/file.php',
{
action: 'send'
},
function(data, textStatus)
{
alert(data);
});
还有一个 PHP 文件:
<?php
/* Some SQL queries here */
echo 'action done';
/* echo response back to jquery and continue other actions here */
?>
默认情况下,jQuery 会等到执行整个 PHP 脚本后才发出警报。有没有办法在执行 PHP 文件的其余部分之前提醒操作已完成??
谢谢
最佳答案
使用普通的 Javascript ajax 是可能的。当请求完成之前收到数据时,onreadystatechange
事件将触发,readyState
为 3。
在下面的示例中,newData
将包含新数据。我们必须做一些处理,因为 XHR 实际上在 responseText
中为我们提供了到目前为止的全部数据,因此如果我们只想知道新数据,我们必须保留最后一个索引的记录。
var httpRequest, lastIndex = 0;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState === 3) {
var newData = httpRequest.responseText.substring(lastIndex);
lastIndex = httpRequest.responseText.length;
console.log(newData);
}
};
httpRequest.open('POST', '/file.php');
httpRequest.send('action=send');
对于 jQuery ajax,this answer建议 jQuery 允许您绑定(bind)到 readystatechange
但我还没有测试过它。
关于php - 如何在完成 PHP 脚本执行之前接收 jQuery post 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17404499/