gpt4 book ai didi

JQuery when() then() 导致缺少 ajax responseText

转载 作者:行者123 更新时间:2023-12-01 00:15:04 28 4
gpt4 key购买 nike

这让我很困惑。我有一个 url 数组(用于数据),我需要将其拉入页面并在全部加载后处理结果。我正在尝试使用 JQuerys Defered 功能来确保在处理结果之前所有 ajax 调用都已完成。一旦我引入它(when().done()功能),我的responseText就神奇地消失了。

我最简单的例子:

$.when([$.ajax("pathToData")]).done(
function(results) {
console.log(results[0]); //object with a responseText attribute
console.log(results[0].responseText); //undefined !!!
}
)

我怀疑我错过了一些简单的东西,但是我阅读文档越多,这看起来就越正确。我希望其他人能够轻松发现问题并为我指出正确的方向。提前致谢!

最佳答案

您看到的奇怪行为是控制台的限制,实际上与您的代码无关。

对象属性的解析会延迟,直到您在控制台中展开对象为止。到那时,AJAX 请求已完成并且 responseText 可用。但是,results[0].responseText 的值会立即解析为 undefined

如果你这样做了:

$.when([$.ajax({
url: '/echo/json/',
type: 'POST',
data: {json: '{"a":12}'}
})]).done(function(results) {
console.log(JSON.stringify(results[0])); //object with a responseText attribute
console.log(results[0].responseText); //undefined !!!
})​

你会看到:

{"readyState": 1}
undefined

相反。

<小时/>

关于如何解决您的问题;我从来不知道 $.when() 接受数组,文档也没有说它接受数组。因此,when() 似乎立即执行 done(),因为该数组不是延迟的(根据文档):

If a single argument is passed to jQuery.when and it is not a Deferred, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

而是将您的 AJAX 请求作为单独的参数传递,如文档中所示:

$.when($.ajax('a'), $.ajax('b')).done(function (a, b) {
// a & b = [ "success", statusText, jqXHR ]
});

因此:

$.when($.ajax({
url: '/echo/json/',
type: 'POST',
data: {json: '{"a":12}'}
}), $.ajax({
url: '/echo/json/',
type: 'POST',
data: {json: '{"b":12}'}
})).done(function(a, b) {
console.log(a[2].responseText);
console.log(b[2].responseText);
})​;

你得到:

{"a": 12}
{"b": 12}

...以及更新的 fiddle :http://jsfiddle.net/39mHw/2/

关于JQuery when() then() 导致缺少 ajax responseText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13939304/

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