Home > Web Front-end > JS Tutorial > What are the ways to implement Ajax asynchronously in native JS?

What are the ways to implement Ajax asynchronously in native JS?

php中世界最好的语言
Release: 2018-04-14 14:21:50
Original
1853 people have browsed it

This time I will bring you the methods of implementing Ajax asynchronous in native JS, and what are the precautions for implementing Ajax asynchronous in native JS. The following is a practical case, let's take a look.

In the process of front-end page development, Ajax requests are often used to submit form data asynchronously or refresh the page asynchronously.

Generally speaking, it is very convenient to use $.ajax, $.post, and $.getJSON in Jquery, but sometimes, we only need the ajax function, so it is not cost-effective to introduce Jquery.

So next, we will use native JavaScrpit to implement a simple Ajax request, and explain the cross-domain access issues in ajax requests, as well as the data synchronization issues of multiple ajax requests.

JavaScript implements Ajax asynchronous request

Simple ajax request implementation

The principle of Ajax request is to create an XMLHttpRequest object and use this object to send requests asynchronously. For specific implementation, please refer to the following code:

function ajax(option) {
  // 创建一个 XMLHttpRequest 对象
  var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"),
    requestData = option.data,
    requestUrl = option.url,
    requestMethod = option.method;
  // 如果是GET请求,需要将option中的参数拼接到URL后面
  if ('POST' != requestMethod && requestData) {
    var query_string = '';
    // 遍历option.data对象,构建GET查询参数
    for(var item in requestData) {
      query_string += item + '=' + requestData[item] + '&';
    }
    // 注意这儿拼接的时候,需要判断是否已经有 ?
    requestUrl.indexOf('?') > -1
      ? requestUrl = requestUrl + '&' + query_string
      : requestUrl = requestUrl + '?' + query_string;
    // GET 请求参数放在URL中,将requestData置为空
    requestData = null;
  }
  // ajax 请求成功之后的回调函数
  xhr.onreadystatechange = function () {
    // readyState=4表示接受响应完毕
    if (xhr.readyState == ("number" == typeof XMLHttpRequest.DONE ? XMLHttpRequest.DONE : 4)) {
      if (200 == xhr.status) { // 判断状态码
        var response = xhr.response || xhr.responseText || {}; // 获取返回值
        // if define success callback, call it, if response is string, convert it to json objcet
        console.log(response);
        option.success && option.success(response); // 调用回调函数处理返回数据
        // 可以判断返回数据类型,对数据进行JSON解析或者XML解析
        // option.success && option.success('string' == typeof response ? JSON.parse(response) : response);
      } else {
        // if define error callback, call it
        option.error && option.error(xhr, xhr.statusText);
      }
    }
  };
  // 发送ajax请求
  xhr.open(requestMethod, requestUrl, true);
  // 请求超时的回调
  xhr.ontimeout = function () {
    option.timeout && option.timeout(xhr, xhr.statusText);
  };
  // 定义超时时间
  xhr.timeout = option.timeout || 0;
  // 设置响应头部,这儿默认设置为json格式,可以定义为其他格式,修改头部即可
  xhr.setRequestHeader && xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
  xhr.withCredentials = (option.xhrFields || {}).withCredentials;
  // 这儿主要用于发送POST请求的数据
  xhr.send(requestData);
}
Copy after login
There are detailed comments in the above code. The principle of ajax is very simple. In general, it uses the XMLHttpRequest object to send data. Here is a supplementary explanation of this object.

Basic properties of XMLHttpRequest object

The readyState attribute has five status values:

0: is uninitialized: not initialized. The XMLHttpRequest object has been created but not initialized.

1: It’s loading: it’s ready to be sent.
2: It is loaded,: It has been sent, but no response has been received yet.
3: It is interactive: the response is being received, but it has not been received yet.
4: Yes completed: Accepting the response is completed.
responseText: The response text returned by the server. It only has a value when readyState>=3. When readyState=3, the response text returned is incomplete. Only readyState=4, the complete response text is received.

responseXML: The response information is xml and can be parsed into a Dom object.

status: The

Http status code of the server. If it is 200, it means OK, and 404 means not found.

statusText: The text of the server http status code. For example, OK, Not Found.

Basic methods of XMLHttpRequest object

open(method, url, asyn): Open XMLHttpRequest object. The methods include get, post, delete, and put. url is the address of the requested resource. The third parameter indicates whether to use asynchronous. The default is true, because the characteristic of Ajax is asynchronous transmission. False if synchronization is used.

send(body): Send request Ajax. The content sent can be the required parameters. If there are no parameters, send directly (null)

Instructions

Just call the ajax function defined above and pass the corresponding options and parameters.

ajax({
  url: '/post.php',
  data: {
    name: 'uusama',
    desc: 'smart'
  },
  method: 'GET',
  success: function(ret) {
    console.log(ret);
  }
});
Copy after login

Cross-domain request issue

When using ajax requests, you must pay attention to one issue: cross-domain requests.

Without using special means, cross-domain requests: When requesting URL resources under other domain names and ports, Access-Control-Allow-Origin related errors will be reported. The main reason is the browser's same-origin policy restriction, which stipulates that cross-domain resource requests cannot be made.

Solution

Some solutions are briefly mentioned below.

Add a header that allows cross-domain requests in the ajax header. This method also requires the server to cooperate with adding a header that allows cross-domain requests. Here is a PHP example of adding a cross-domain header that allows POST requests:

// 指定允许其他域名访问 
header('Access-Control-Allow-Origin:*'); 
// 响应类型 
header('Access-Control-Allow-Methods:POST'); 
// 响应头设置 
header('Access-Control-Allow-Headers:x-requested-with,content-type');
Copy after login
Using dynamic scrpit tags, the method of dynamically creating a scrpit tag and pointing it to the requested address, that is, the JSONP method, requires splicing a callback function after the URL. The callback function will be called after the tag is loaded successfully.

var url = "http://uusama.com", callbaclName = 'jsonpCallback';
script = document.createElement('script');
script.type = 'text/javascript';
script.src = url + (url.indexOf('?') > -1 ? '&' : '?') + 'callback=' + callbaclName;
document.body.appendChild(script);
Copy after login
The callback function needs to be set as

global function:

window['jsonpCallback'] = function jsonpCallback(ret) {}

Multiple ajax request data synchronization problem

Asynchronous processing of single ajax return data

Multiple ajax requests are not related to each other. They send their own requests after being called. After the request is successful, they call their own callback methods without affecting each other.

因为ajax请求异步的特性,所有一些依赖于请求完成之后的操作我们都需要放在回调函数内部,否则的话,你在回调函数外面读取到的值是空。看下面的例子:

var result = null;
ajax({
  url: '/get.php?id=1',
  method: 'GET',
  success: function(ret) {
    result = ret;
  }
});
console.log(result); // 输出 null
Copy after login

虽然我们在回调函数里面设置了result的值,但是在最后一行 console.log(result); 输出为空。

因为ajax请求是异步的,程序执行到最后一行的时候,请求并没有完成,值并没有来得及修改。

这儿我们应该把 console.log(result) 相关的处理,放在 success 回调函数中才可以。

多个ajax返回数据问题

如果有多个ajax请求,情况会变得有些复杂。

如果多个ajax请求是按照顺序执行的,其中一个完成之后,才能进行下一个,则可以把后面一个请求放在前一后请求的回调中。

比如有两个ajax请求,其中一个请求的数据依赖于另外一个,则可以在第一个请求的回调里面再进行ajax请求:

// 首先请求第一个ajax
ajax({
  url: '/get1.php?id=1',
  success: function(ret1) {
    // 第一个请求成功回调以后,再请求第二个
    if (ret1) {
      ajax({
        url: '/get2.php?id=4',
        success:function(ret2) {
          console.log(ret1);
          console.log(ret2)
        }
      })
    }
  }
});
// 也可以写成下面的形式
// 将第二个ajax请求定义为一个函数,然后调用
var ajax2 = function(ret1) {
  ajax({
    url: '/get2.php?id=4',
    success:function(ret2) {
      console.log(ret1);
      console.log(ret2)
    }
  });
};
ajax({
  url: '/get1.php?id=1',
  success: function(ret1) {
    if(ret1){
      ajax2(ret1); // 调用第二个ajax请求
    }
  }
});
Copy after login

如果不关心不同的ajax请求的顺序,而只是关心所有请求都完成,才能进行下一步。

一种方法是可以在每个请求完成以后都调用同一个回调函数,只有次数减少到0才执行下一步。

var count = 3, all_ret = []; // 调用3次
ajax({
  url: '/get1.php?id=1',
  success:function(ret) {
    callback(ret); // 请求成功后调用统一回调,次数减1
  }
});
ajax({
  url: '/get2.php?id=1',
  success:function(ret) {
    callback(ret);
  }
});
ajax({
  url: '/get3.php?id=1',
  success:function(ret) {
    callback(ret);
  }
});
function callback(ret) {
  // 当调用3次以上以后,说明3个ajax军完成
  if (count > 0) {
    count--; // 每调用一次,次数减1
    // 可以在这儿保存 ret 到全局变量
    all_ret.push(ret);
    return;
  } else { // 调用三次以后
    // todo
    console.log(ret);
  }
}
Copy after login

另一种方法是设置一个定时任务去轮训是否所有ajax请求都完成,需要在每个ajax的成功回调中去设置一个标志。

这儿可以用是否获得值来判断,也可以设置标签来判断,用值来判断时,要注意设置的值和初始相同的情况。

var all_ret = {
  ret1: null, // 第一个ajax标识
  ret2: null, // 第二个ajax标识
  ret3: null, // 第三个ajax标识
};
ajax({
  url: '/get1.php?id=1',
  success:function(ret) {
    all_ret['ret1'] = ret; // 修改第一个ajax请求标识
  }
});
ajax({
  url: '/get2.php?id=1',
  success:function(ret) {
    all_ret['ret2'] = ret; // 修改第二个ajax请求标识
  }
});
ajax({
  url: '/get3.php?id=1',
  success:function(ret) {
    all_ret['ret3'] = ret; // 修改第三个ajax请求标识
  }
});
var repeat = setInterval(function(){
  // 遍历是否所有ajax请求标识都已被修改,以此判断是否所有ajax请求都已完成
  for(var item in all_ret) {
    if (all_ret[item] === null){
      return;
    }
  }
  // todo, 到这儿所有ajax请求均已完成
  clearInterval(repeat);
}, 50); // 调用次数可以适当调整,不应设的过小或者过大
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

datatable怎样实现异步加载

在IE11下里使用canvas.toDataURL兼容性问题的解决思路

The above is the detailed content of What are the ways to implement Ajax asynchronously in native JS?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template