JQuery中使用Ajax时无法给全局变量赋值的解决方案
在JS函数里面用了AJAX,然后就发现怎么里面都赋值不了给全局变量,原来是异步的问题,如下:
我们在用JQuery的Ajax从后台提取数据后想把它赋值给全局变量,但是却怎么都赋不进,为什么呢?
原因其实很简单,我们用的Ajax是异步操作,也就是说在你赋值的时候数据还没提取出来,你当然赋不进去,所以只要改成同步操作就行了。
方法1:先设置同步在进行Ajax操作
//在全局或某个需要的函数内设置Ajax异步为false,也就是同步
$.ajaxSetup({ async : false });
//然后再进行你的Ajax操作
$.post(地址, 参数, function(data, status) {
if (status == "success"){//赋值给全局变量
}else{
alert("wrong");}
});
方法1:直接用$.ajax
$.ajax({
type : "post",
url :地址,
data : "参数" + 参数的值,
async : false,
success : function(data){
//赋值给全局变量;}
});
最重要的就是async : false了这个就是设置同步异步的了。
Jquery的ajax提交时显示“加载中”的代码 Jquery Ajax中post和get默认是同步还是异步的
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
No one can deny from the feature of this movie posted at this website, pleasant work,keep it always the time.
Wow! Finally I got a network site from where I be learned of among fact get profitable information regarding my study and knowledge.