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

How to implement Ajax with asynchronous requests in native JS

Apr 16, 2018 am 10:48 AM
javascript accomplish ask

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

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);
  }
});
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, 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');
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 a global function:

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

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
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)
        }
      })
    }
  }
});
// 也可以写成下面的形式
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);
    }
  }
});
Copy after login

如果不关心不同的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);
  }
}
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

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>
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

How to implement exact division operation in Golang How to implement exact division operation in Golang Feb 20, 2024 pm 10:51 PM

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

Using PHP to implement SaaS: a comprehensive analysis Using PHP to implement SaaS: a comprehensive analysis Mar 07, 2024 pm 10:18 PM

I'm really sorry that I can't provide real-time programming guidance, but I can provide you with a code example to give you a better understanding of how to use PHP to implement SaaS. The following is an article within 1,500 words, titled "Using PHP to implement SaaS: A comprehensive analysis." In today's information age, SaaS (Software as a Service) has become the mainstream way for enterprises and individuals to use software. It provides a more flexible and convenient way to access software. With SaaS, users don’t need to be on-premises

Detailed explanation of using Golang to implement data export function Detailed explanation of using Golang to implement data export function Feb 28, 2024 pm 01:42 PM

Title: Detailed explanation of data export function using Golang. With the improvement of informatization, many enterprises and organizations need to export data stored in databases into different formats for data analysis, report generation and other purposes. This article will introduce how to use the Golang programming language to implement the data export function, including detailed steps to connect to the database, query data, and export data to files, and provide specific code examples. To connect to the database first, we need to use the database driver provided in Golang, such as da

See all articles