将网络请求从同步转换为异步(PHP/Javascript)


Convert network request from synchronous to asynchronous (PHP/Javascript)

我实际上为广告网络使用php脚本,但是发布者将使用的代码是同步的。现在,我希望脚本以异步方式加载。

我需要改变所有的PHP/Javascript代码吗?或者有一个技巧可以使用(javascript库…)

感谢您的帮助

我不完全确定,但我认为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;

同步/异步取决于客户端。除非非常特殊的例外。

所以关注Javascript代码。: https://developer.mozilla.org/en-US/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代码中完成的地方,并将一个更改为另一个。