[英]How to receive jQuery post response before completing execution of PHP script?
我有一個簡單的jquery函數,可以將發布請求發送到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腳本后再發出警報。 before executing the rest of the PHP file?? 有沒有一種方法可以在執行其余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, 此答案表明jQuery可讓您綁定到readystatechange
但我尚未對其進行測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.