[英]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.