2011-06-25 93 views
0

的異常行爲我寫了下面的代碼:jQuery的AJAX功能的成功

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

雖然警報給了我什麼responseText最好應該給當我從GlassFish中使用。但是當我在VS中加載完全相同的文件時,令我驚恐的是,我得到了[Object]作爲alert的輸出。 有什麼問題?

順便說一下,我返回的是XML而不是JSON。

+0

是什麼讓你認爲這與成功回調而不是'alert'或者你自己調用的頁面有關? – Jon

+0

沒有得到你..一個無辜的警報可能是錯誤的? – mihsathe

+0

沒有什麼與'alert'本身 - 而是它的輸入。但這不是可憐的回調的錯。 – Jon

回答

1

jquery默認會對您的數據類型執行「智能猜測」並傳遞成功函數格式爲的響應。因此,例如,如果您的url提供json數據,則成功函數將傳遞解析的json對象,而不僅僅是一個字符串。所以alert({...})將顯示[object Object]

如果你只想文本輸出,使用方法:

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

同意。現在我認爲這是'智能地'返回XMLDom解析對象。但是我仍然想知道爲什麼之前在jsp頁面中嘗試時返回了文本? – mihsathe

0

我會懷疑,在第二種情況下返回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.*/ 
}) 
}});