jQuery ajax函数的异常行为's的成功

anomalous behaviours of jQuery ajax function's success

本文关键字:成功 ajax 函数 异常 jQuery      更新时间:2023-09-26

我写了以下代码:

$.ajax({ url: link + "?" + Math.random(), success: function (response) {
            alert(response);
}});

尽管警报告诉了我在使用玻璃鱼时responseText的理想值。但当我在VS中加载完全相同的文件时,令我恐惧的是,我得到了[Object]作为alert的输出。怎么了?

顺便说一下,我返回的是XML而不是JSON。

默认情况下,jquery将对您的数据类型执行"智能猜测",并将格式的响应传递给成功函数。因此,例如,如果您的url提供json数据,那么成功函数将获得解析后的json对象,而不仅仅是字符串。因此alert({...})将显示[object Object]

如果您只想要文本输出,请使用:

$.ajax({
   url: link + "?" + Math.random(),
   success: function (response) { alert(response); },
   dataType: 'text'
});

我怀疑在返回JSON的第二种情况下,您需要执行以下操作:

$.ajax({ url: link + "?" + Math.random(), success: function (response) {
            $(response).each(function() {
/*do something with data, firefox with firebug allows you to do console.log($this) which will show you the data in a window below the browser, Chrome also has a similar feature, alerting in an iterator is never a good idea.*/
})
}});