gpt4 book ai didi

javascript - 使用 jQuery 迭代 JSON 对象数组时出现奇怪的行为

转载 作者:行者123 更新时间:2023-12-02 20:04:22 26 4
gpt4 key购买 nike

这是我的 JSON 响应示例:

[{"id":11137,"name":"Agra"},{"id":11138,"name":"Albizzate"}]

我需要迭代每个数组对象并打印idname:

        $.ajax({
url: '{{ path('ajax_provinces') }}',
type: 'POST',
dataType: 'json',
data: {region_id: this.value},
success: function(provinces) {},
error: function() { alert("error"); },
complete: function(provinces) {
$('select#regions ~ span > img').fadeOut('slow');
$.each(provinces, function(key, val) {
alert(key + ": " + val);
});
}
});

问题是我得到了奇怪的结果:函数名称、函数体和来自 jQuery 的其他内部内容。看起来就像是迭代 jQuery 库函数!知道发生了什么吗?

最佳答案

问题是 complete 回调没有将返回的数据作为参数传递:

complete(jqXHR, textStatus)

A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

( from the docs )

大概您看到的奇怪键/值是 jqXHR 对象的属性。

您需要以success处理返回的数据,而不是complete。我的理解是,complete 通常用于无论 AJAX 请求是否成功返回数据都应该发生的操作(例如隐藏加载动画)。

关于javascript - 使用 jQuery 迭代 JSON 对象数组时出现奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7627209/

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