Home > Web Front-end > JS Tutorial > body text

Detailed explanation of usage examples of $.getJSON asynchronous and synchronous requests

伊谢尔伦
Release: 2017-07-21 14:56:33
Original
2008 people have browsed it

A previous function wanted to call the return value of the previous function, but its return value was always empty. Later, after looking through some information, I realized that asynchronous requests were causing trouble. I won’t go into details, but look at the example:


function get_no_order_array() { 
  var order_info = show_order(); 
  var order = []; 
  
  $.getJSON("../JSON/customers.json", function (date) { 
 
    date["man"].forEach(function (person) { 
      if (order_info.k_obj[person] == undefined) { 
        order.push(person); 
      } 
    }) 
  }); 
 
  return order; 
}
Copy after login

Later I found that the printed array order was always empty. The following is the corrected code:


function get_no_order_array() { 
  var order_info = show_order(); 
  var order = []; 
  $.ajaxSettings.async = false;//在执行之前加$.ajaxSettings.async = false;  (同步执行) 
  $.getJSON("../JSON/customers.json", function (date) { //<span style="line-height: 1.5;">$.getJSON不懂的话可以看一下我之前的博客,或是专门学习一下  “JSON”</span>
Copy after login


date["man"].forEach(function (person) { 
      if (order_info.k_obj[person] == undefined) { 
        order.push(person); 
      } 
    }) 
  }); 
  $.ajaxSettings.async = true;//执行你的代码之后及时恢复为$.ajaxSettings.async = true; (异步执行) 
  return order; 
}
Copy after login

Add $.ajaxSettings.async = false; before the loop to indicate synchronous execution, so that it will be executed in order.

Solution to the problem of data confusion caused by executing multiple $.getJSON() at the same time

Add $.ajaxSettings.async = false; before execution (synchronous execution)

Execution Your code will be restored to $.ajaxSettings.async = true in time; (asynchronous execution)

Otherwise, it will affect the code in other places that needs to be executed asynchronously.


$.ajaxSettings.async = false;

$.getJSON(url, data, function(data){ });

$.getJSON(url, data, function(data){ });

$.getJSON(url, data, function(data){ });

......

$.ajaxSettings.async = true;
Copy after login

The above is the detailed content of Detailed explanation of usage examples of $.getJSON asynchronous and synchronous requests. 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