async in Ajax Request: false and true Function of ajax Call Externally

  • 2021-07-18 06:45:25
  • OfStack

test.html


<a href="javascript:void(0)" rel="external nofollow" onmouseover="testAsync()">
asy.js

function testAsync(){
  var temp;
  $.ajax({
    async: false,  // Synchronization request 
    type : "GET",
    url : 'tet.php',
    complete: function(msg){
      alert('complete');
    },
    success : function(data) {
      alert('success');
      temp=data;
    }
  });
  alert(temp);
}

tet.php


<?php
  echo "here is html code";
  sleep(5);
?>

Description

async: false, (default is true);

As above: false is synchronization, and the Ajax request in this testAsync () method locks the whole browser, and other operations can only be performed after tet. php is executed.

When async: true, ajax requests are asynchronous.

However, there is a problem: the ajax request and its subsequent operations in testAsync () are executed asynchronously, so when tet. php has not been executed, the operations after ajax request may have been executed, such as alert (temp + 'end'); However, temp is assigned only after ajax requests success, and the output will be null.

----------------------------------------------------

Because ajax is called asynchronously by default, it is rare to get the return value of ajax directly. But sometimes you have to get it through ajax because of business needs, so I offer two solutions here.

Specific methods:

1. Just like setting async: false to make it asynchronous and synchronous;

2. You can execute the parameters you need to use next within success.

Of these two schemes, you choose one according to the actual situation of your project.

Relatively speaking, if you don't have too much performance requirements, you can choose.


Related articles: