jQuery ajax调用async:false与async:true [英] jQuery ajax calls async: false vs async: true
问题描述
我正在尝试使用jQuery ajax函数异步加载html.但是由于某种原因,我只能在async为false的情况下使用.我正在使用jQuery网站上的代码示例,但看不到为什么不起作用? 我使用的是Firefox浏览器,我在IE 8中进行了尝试,异步:真正的功能在那里.
I am trying to load html asynchronously using jQuery ajax function. But I for some reason, it only works if async is false. I am using code sample from jQuery website, I don't see why it wouldn't work? I am using Firefox browser, I tried it in IE 8, async: true works there.
警告表明数据为空:
$.ajax({
url: 'test.html',
async: true,
success: function (data) { alert(data); }
});
数据随test.html的内容一起返回:
Data comes back with content of test.html :
$.ajax({
url: 'test.html',
async: false,
success: function (data) { alert(data); }
});
足够奇怪的是,它可以工作:
Strangely enough this makes it work:
var response = $.ajax({
url: 'test.html',
async: true,
success: function (data) { alert(data); }
});
alert(response);
这是怎么回事?
推荐答案
确定,发现:单击按钮时会触发ajax调用,但是该按钮正在提交表单,因此整个页面都在重新加载.添加"return false";单击事件以防止按钮提交表单有所不同.
OK, figured it out: ajax call was firing on button click, but that button was submiting the form, so the whole page was reloading. Adding "return false;" to click event to prevent button from submitting the form made the difference.
这篇关于jQuery ajax调用async:false与async:true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!