jQuery 脚本应该异步运行但只能同步运行?为什么?
我有这个小 jquery 脚本,如果删除“async:false”部分,它就不起作用...而且我不明白为什么(alert() 部分只是为了检查它是否有效)。我的猜测是它会异步工作,但事实并非如此。有人可以向我解释为什么吗?我应该改变什么来使其异步?
$(document).ready(function(){
var artistName = new Array();
var artistPlaycount = new Array();
$('#inputForm').submit(function(){
var userName = $('#username').attr('value');
var amount = $('#amount').attr('value');
userName = "someUsername";
$.ajax({
type: "POST",
url: "prepXML.php",
data: "method=getartists&user="+userName+"&amount="+amount,
dataType: "xml",
async:false,
success: function(xml){
var i = 0;
$("artist",xml).each(function(){
artistName[i] = $(this).find("name").text();
artistPlaycount[i] = $(this).find("playcount").text();
i++;
});
}
});
});
alert(artistName[2]); //or any other iteration number
});
谢谢
I have this small jquery script that does not work if I remove the 'async:false' part... And I don't understand why (the alert() part is there just to check if it works or not). My guess was it would work asynchronously but it just doesn't. Can somebody explain to me why? And what should I change to make it async?
$(document).ready(function(){
var artistName = new Array();
var artistPlaycount = new Array();
$('#inputForm').submit(function(){
var userName = $('#username').attr('value');
var amount = $('#amount').attr('value');
userName = "someUsername";
$.ajax({
type: "POST",
url: "prepXML.php",
data: "method=getartists&user="+userName+"&amount="+amount,
dataType: "xml",
async:false,
success: function(xml){
var i = 0;
$("artist",xml).each(function(){
artistName[i] = $(this).find("name").text();
artistPlaycount[i] = $(this).find("playcount").text();
i++;
});
}
});
});
alert(artistName[2]); //or any other iteration number
});
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要异步执行此操作,您需要将警报移至回调中并删除
async
选项,如下所示:否则填充数组的
success
函数将在之后发生em> 警报确实...所以你想要的还没有完成。直到请求从服务器返回后,success
处理程序才会执行。此外,
.each()
回调的第一个参数是索引,你可以使用它,不需要保留你自己的递增变量:)To do this asynchronously you need to move the alert into the callback and remove the
async
option, like this:Otherwise that
success
function populating the array happens after the alert does...so what you want isn't quite there yet. Not until the request comes back from the server does thesuccess
handler execute.Also, the first parameter to the
.each()
callback is the index, you can use it, no need to keep your own incrementing variable :)它不起作用,因为回调是在
警报
之后触发的。将警报
放入回调中。It doesn't work because the callback is fired after the
alert
. Put thealert
in the callback.您需要将警报移至成功处理程序中。
应该在循环完 xml 之后立即执行。
所以你应该有:
you need to move the alert into your success handler.
should go right after you loop through the xml.
so you should have: