Home >Web Front-end >JS Tutorial >Solution to exception when assigning values ​​to global variables using Ajax in JQuery_jquery

Solution to exception when assigning values ​​to global variables using Ajax in JQuery_jquery

WBOY
WBOYOriginal
2016-05-16 17:04:341159browse

After we use JQuery’s Ajax to extract data from the background, we want to assign it to a global variable, but we can’t assign it. Why?

The reason is actually very simple. The Ajax we use is an asynchronous operation, which means that the data has not been extracted when you assign the value. Of course, you cannot assign it, so you only need to change it to a synchronous operation~

Method 1: Set up synchronization before performing Ajax operation

Copy code The code is as follows:

//Set Ajax asynchronous to false globally or within a required function, that is, synchronization
$.ajaxSetup({
async : false
});

//Then perform your Ajax operation
$.post(address, parameter, function(data, status) {
if (status == "success") {
//Assign value to Global variables
}
else {
      alert("wrong");
    }
}); ajax



Copy code
The code is as follows: $.ajax({ type: "post",
url: address,
data: "parameter" parameter value,
async: false,
success: function(data){
//Assign value to global Variable;
}
});


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