search
HomeWeb Front-endJS TutorialDetailed explanation of Ajax asynchronous request examples using JavaScript

This article mainly shares with you a detailed explanation of the implementation of Ajax asynchronous request using JavaScript. Ajax is now a very popular technology. Although you can now use JQuery or some third-party plug-ins or even some controls provided by Microsoft to implement the ajax function, but It is also very important to understand its principle. The following is to use pure javascript to obtain server-side functions to show how to use pure javascript to implement ajax function to clarify its principle.

In the process of front-end page development, it is often Use Ajax requests 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, 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. Please refer to the following code for specific implementation:


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.

Basic properties of the XMLHttpRequest object

The readyState property 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 the 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)

Using method

Directly call the ajax function defined above and transfer the corresponding options and parameters That’s it.


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, 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

Here are some simple solutions.

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, a method of dynamically creating a scrpit tag and pointing it to the requested address, also It is the JSONP method. You need to splice 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
Multiple ajax requests are not related to each other. They send their own requests after being called, and the request is successful. Calling your own callback methods in the future will not affect each other.

Because of the asynchronous nature of ajax requests, all operations that depend on the completion of the request need to be placed inside the callback function. Otherwise, the value you read outside the callback function will be empty. Look at the following example:


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

Although we set the result value in the callback function, the output of console.log(result); in the last line is empty.

Because the ajax request is asynchronous, when the program executes to the last line, the request is not completed and the value has not had time to be modified.

Here we should put console.log(result) related processing in the success callback function.

The problem of multiple ajax returning data

If there are multiple ajax requests, the situation will become a little complicated.

如果多个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请求
    }
  }
});

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

另一种方法是设置一个定时任务去轮训是否所有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); // 调用次数可以适当调整,不应设的过小或者过大

相关推荐:

ajax异步请求刷新方法

jquery请求servlet实现ajax异步请求实例分享

实例分析Ajax异步请求技术

The above is the detailed content of Detailed explanation of Ajax asynchronous request examples using JavaScript. 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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.