gpt4 book ai didi

javascript - jQuery 脚本应该异步运行但只能同步运行?为什么?

转载 作者:行者123 更新时间:2023-11-30 23:44:32 25 4
gpt4 key购买 nike

我有这个小 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
});

谢谢

最佳答案

要异步执行此操作,您需要将警报移至回调中并删除 async 选项,如下所示:

    $.ajax({  
type: "POST",
url: "prepXML.php",
data: "method=getartists&user="+userName+"&amount="+amount,
dataType: "xml",
success: function(xml){
$("artist",xml).each(function(i){
artistName[i] = $(this).find("name").text();
artistPlaycount[i] = $(this).find("playcount").text();
});
alert(artistName[2]);
}
});

否则,success 函数填充数组警报执行之后发生......所以您想要的还没有完成。直到请求从服务器返回后,success 处理程序才会执行。

此外,.each() 的第一个参数回调是索引,你可以使用它,不需要保留你自己的递增变量:)

关于javascript - jQuery 脚本应该异步运行但只能同步运行?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3505388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com