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

Solution to the failure exception when using Ajax to assign values ​​to global variables in JQuery_jquery

WBOY
Release: 2016-05-16 16:39:19
Original
1458 people have browsed it

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 first and then perform Ajax operation

//在全局或某个需要的函数内设置Ajax异步为false,也就是同步
$.ajaxSetup({ 
async :false});

//然后再进行你的Ajax操作
$.post(地址,参数,function(data, status){if(status =="success"){//赋值给全局变量}else{ 
alert("wrong");}});
Copy after login

Method 2: Use $.ajax directly

$.ajax({ 
type :"post", 
url :地址, 
data :"参数"+参数的值, 
async :false, 
success :function(data){//赋值给全局变量;}});
Copy after login

Example code:

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