Home>Article>Web Front-end> How to change ajax request from asynchronous to synchronous

How to change ajax request from asynchronous to synchronous

青灯夜游
青灯夜游 Original
2022-01-17 16:28:32 6182browse

AJAX can be divided into synchronous and asynchronous according to the different async values. By default, the async value is true (asynchronous submission); if you want to change asynchronous to synchronous, you only need to set the async value to false. Can.

How to change ajax request from asynchronous to synchronous

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

AJAX is divided into synchronous (async = false) and asynchronous (async = true) according to the value of async

By default, async is true (asynchronous submission).

If you want to synchronize, just set async to false.

Example:

When using AJAX, occasionally you will encounter the need to get an array and the id corresponding to the data from one interface, and then get the data on another interface. , the initial writing method is as follows:

$.get(url_1, function (data) { var dom = []; for (var i = 0; i < data.length; i++) { var item = data[i]; //两个url不一致,根据id查找另一个表 $.get(url_2, function (data) { var item_result = data; dom.push("
item_result.id
"); }); } $("#id").empty().append(dom.join('')); });

However, at this time, there is often a problem that no data is written after the array is cleared. Beginners often mistakenly think that the interface is wrong. In fact, it is not the case.

This is because Ajax methods such as $get() take time when calling the interface, causing the append behavior to occur before the push is completed, that is, the array is cleared at this time, but there is no data read by join in the dom array at this time

Therefore, the Ajax in the loop needs to be modified to be synchronized here. The code modification is as follows:

$.get(url_1, function (data) { var dom = []; for (var i = 0; i < data.length; i++) { var item = data[i]; //在第二次的Ajax前将异步改同步 $.ajaxSettings.async = false; //两个url不一致,根据id查找另一个表 $.get(url_2, function (data) { var item_result = data; dom.push("
item_result.id
"); }); //注意在ajax中的push完成后,将其改回异步 $.ajaxSettings.async = true; } $("#id").empty().append(dom.join('')); });

[Related tutorial recommendations:AJAX video tutorial]

The above is the detailed content of How to change ajax request from asynchronous to synchronous. 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