Home  >  Article  >  Web Front-end  >  How to implement Ajax with asynchronous requests in native JS

How to implement Ajax with asynchronous requests in native JS

php中世界最好的语言
php中世界最好的语言Original
2018-04-16 10:48:262068browse

This time I will show you how to implement Ajax with native JS asynchronous requests. What are the precautions for implementing Ajax with native JS asynchronous requests? 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, $.getJSON in Jquery, but sometimes, it is not cost-effective to introduce Jquery just because we need the ajax function.

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);
}
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.

The short-circuiting properties of many Boolean expressions are used in the code to replace the writing of conditional statements. Making good use of the short-circuiting properties of Boolean expressions can simplify a large number of simple conditional statements. ^_^

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: Yes loading: ready to be sent.

2: is loaded,: 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);
  }
});

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, an error message will be reported. Access-Control-Allow-Origin related errors. 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');
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);
The callback function needs to be set as a global function:

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

Multiple ajax request data synchronization issues

Asynchronous processing of single ajax return data

多个ajax请求互不相关,它们在被调用以后发送各自请求,请求成功以后调用自己的回调方法,互不影响。 因为ajax请求异步的特性,所有一些依赖于请求完成之后的操作我们都需要放在回调函数内部,否则的话,你在回调函数外面读取到的值是空。看下面的例子:

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

虽然我们在回调函数里面设置了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)
        }
      })
    }
  }
});
// 也可以写成下面的形式
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请求的顺序,而只是关心所有请求都完成,才能进行下一步。 一种方法是可以在每个请求完成以后都调用同一个回调函数,只有次数减少到0才执行下一步。

var count = 3, all_ret = []; // 调用3次
ajax({
  url: '/get1.php?id=1',
  success:function(ret) {
    callback(ret);
  }
});
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) {
  if (count > 0) {
    count--;
    // 可以在这儿保存 ret 到全局变量
    all_ret.push(ret);
    return;
  } else { // 调用三次以后
    // todo
    console.log(ret);
  }
}

另一种方法是设置一个定时任务去轮训是否所有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);

PS:下面看下ajax异步请求实例代码,具体代码如下所示:

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>获得书籍列表</title>
<script type="text/javascript">
var xmlhttp;
var txt,x,xx,i;
function loadXMLDoc(url,cfunc)
{
if(window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
 xmlhttp.onreadystatechange = cfunc;
 xmlhttp.open("GET", "<%=request.getContextPath()%>"+url, true);
 xmlhttp.send();
}
function myFunction1()
{
loadXMLDoc("/xmls/books.xml",function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName_r("title");
for(i=0;i<x.length;i++)
{
txt = txt + x[i].childNodes[0].nodeValue+"<br/>";
}
document.getElementByIdx_x("myp").innerHTML = txt;
}
});
}
  function myFunction2()
  {
  loadXMLDoc("/text/test1.txt",function(){
  if(xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  document.getElementByIdx_x("myp").innerHTML = xmlhttp.responseText;
  }
  });
  }
  function myFunction3()
  {
  loadXMLDoc("/xmls/cd_catalog.xml",function(){
  if(xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  txt="<table border=&#39;1&#39;><tr><th>Title</th><th>Artist</th></tr>"
  x= xmlhttp.responseXML.documentElement.getElementsByTagName_r("CD");
  for(i=0;i<x.length;i++)
  {
  txt = txt + "<tr>";
  xx = x[i].getElementsByTagName_r("TITLE");
  {
  try{
  txt = txt + "<td>" + xx[0].firstChild.nodeValue +"</td>";
   }
  catch(er)
  {
  txt = txt +"<td></td>";
  }
  xx = x[i].getElementsByTagName_r("ARTIST");
  try
  {
  txt = txt + "<td>" + xx[0].firstChild.nodeValue +"</td>";
  }
  catch(er)
  {
  txt = txt + "<td></td>";
  }
  }
  txt = txt + "</tr>"
  }
  txt = txt + "</table>";
  document.getElementByIdx_x("myp").innerHTML =txt;
  }
  });
  }
</script>
</head>
<body>
<h2>My Book Collection:</h2>
<button type="button" onClick="myFunction1()">获得我的图书收藏列表</button>
<button type="button" onClick="myFunction2()">这是不同的请求</button>
<button type="button" onClick="myFunction3()">获取CD信息</button>
<p id="myp"></p>
</body>
</html>

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

推荐阅读:



The above is the detailed content of How to implement Ajax with asynchronous requests in native JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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