Home > Web Front-end > JS Tutorial > A brief analysis of the reasons why global variables cannot be assigned values ​​in jquery ajax asynchronous calling methods and their solutions_jquery

A brief analysis of the reasons why global variables cannot be assigned values ​​in jquery ajax asynchronous calling methods and their solutions_jquery

WBOY
Release: 2016-05-16 17:04:32
Original
1145 people have browsed it

When calling a jquery ajax method, we sometimes need the method to return a value or assign a value to a global variable, but we find that the value we want is not obtained after the program is executed. This is very likely It’s because you are using ajax’s asynchronous call async:true (default), such as:

Copy code The code is as follows:

function ManageCommentText(text) {
var result = text;
$.ajax({
data: "get",
url: "GetComments.aspx",
data: "type=getText&commentText=" text,
cache: false,
async: false,
success: function (data) {
result = data;
}
})
return result;

The above method is a synchronous call of ajax. Only after the data value is obtained and assigned to the result, the result will be returned to complete the call of the method. If set to async:true,
will return the result before getting the data value.

Another solution is to write your code directly into the success method. (Depending on your business, not everything can be written directly into success).

Note: If set to async: false, the advantages of ajax asynchronousness will be lost.

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