[英]Convert network request from synchronous to asynchronous (PHP/Javascript)
我實際上在廣告網絡中使用了php腳本,但是發布者將使用的代碼是同步的。 現在,我希望腳本將異步加載。
我是否需要更改所有PHP / Javascript代碼? 或者有一個使用技巧(javascript庫...)
謝謝您的幫助 !
同步/異步取決於客戶端。 除非非常特殊的例外。
因此,請專注於Javascript代碼 。: https : //developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
編輯示例:將文件發送到控制台日志
這是異步XMLHttpRequest的最簡單用法。
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://bar/foo.txt", true/*ASYNCHRONOUS*/);
/* here is registered what-to-do once xhr is 'done':
it can happens anywhen, it is Asynchronous: */
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
相反 ,這是同步的 :
var request = new XMLHttpRequest();
request.open('GET', 'http://...', false/*ASYNCHRONOUS=false, it is SYNCHRONOUS)*/
request.send(null);
/*anything else is stopped around, one thread working only:request*/
/*once it is done, the next line is executed. This is:*/
if (request.status === 200) {
console.log(request.responseText);
}
因此,請在您的JS代碼中獲取完成JS Sync方法的位置,然后將其中一個更改為另一個。
我不確定,但我認為jQuery Ajax調用是您想要的。 http://api.jquery.com/jquery.ajax/
這里是示例ajax調用:
$.ajax({
url: formURL,
type: "POST",
data: postData,
beforeSend: function() {
//this code always run Ususaly UI changes
},
success: function(data, textStatus, jqXHR) {
//var result = JSON.parse(data);
},
error: function(jqXHR, textStatus, errorThrown) {
//if ajax fails
},
complete: function(response) {
// this code always run Ususaly UI changes
}
});
同樣,由於PHP總是返回字符串,因此,您可以簡單地使用以下命令來獲得成功:
"echo $string;"
如果要返回數組,則應該:
"echo json_encode($array);"
對於錯誤部分,最好強制PHP返回錯誤,例如:
header('HTTP/1.1 422 Unprocessable Entity');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode($errors));
exit;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.