2010-04-26 44 views
3

我無法得到響應,從一個jQuery Ajax調用回...jQuery的獲得陣列的詳細信息

(這是一個腳本來驗證用戶身份,並需要返回他們的名字和用戶ID。我的理解是我可以對其進行編碼,如JSON和下面的格式獲取數據。

它的警報()

的JavaScript

返回的「不確定」的錯誤
$.ajax({ 
type: "POST", 
url: "myURL.php", 
data: {username: username, password: password}, 
success: function(results) { 
    //THIS IS WHERE THE PROBLEM IS 
    alert('Hi '+results.name); //Should be "Hi Basil Fawlty" 
    } 
}); 

的PHP(myURL.php)

//This comes from a SQL call that returns the following name 
json_encode(array(
'id'=>1, 
'name'=>'Basil Fawlty' 
)); 

在哪裏我錯了,將不勝感激任何幫助或想法!

謝謝。

解決方案:解決方案是添加dataType。

+0

您使用的是哪個版本的jQuery? – webbiedave 2010-04-26 18:10:55

+1

你可以在這裏發佈你的** alert(results.responceText)**嗎? – 2010-04-26 19:10:21

+0

我使用的是1.3版本。 輸出「未定義」 – Matt 2010-04-27 03:26:22

回答

4

你錯過dataType: "json"

$.ajax({ 
type: "POST", 
url: "myURL.php", 
dataType: "json", 
data: {username: username, password: password}, 
success: function(results) { 
    //THIS IS WHERE THE PROBLEM IS 
    alert('Hi '+results.name); //Should be "Hi Basil Fawlty" 
    } 
}); 

另一個(更簡潔)的選擇是jQuery.getJSON如果你知道你得到JSON。

+0

感謝您的快速回復! – Matt 2010-04-27 03:28:40

1

務必將dataType設置爲JSON讓您得到響應對象的成功方法,像這樣:

$.ajax({ 
type: "POST", 
url: "myURL.php", 
dataType: "json", 
data: {username: username, password: password}, 
success: function(results) { 
    alert('Hi '+results.name); 
} 
}); 

Details for dataType can be found here

另外,you can do this

$.getJSON("myURL.php", {username: username, password: password}, 
    function(results) { 
    alert('Hi '+results.name); 
}); 
+0

感謝您獲取dataType的鏈接以及getJSON的相關信息。 – Matt 2010-04-27 03:29:11

1

我的猜測是,你期待JSON,但你得到的字符串。

1

您也需要在請求中指定數據類型,像這樣:

$.ajax({ 
type: "POST", 
url: "myURL.php", 
data: {username: username, password: password}, 
dataType: "json", 
success: function(results) { 
    //THIS IS WHERE THE PROBLEM IS 
    alert('Hi '+results.name); //Should be "Hi Basil Fawlty" 
    } 
}); 

,或者你可以的,如果你使用jQuery < 1.4使用

header("Content-Type: application/json"); 
3

設置從PHP內容類型,你必須指定dataType: "json"

從1.4,dataType默認爲:

智能猜測(XML,JSON,腳本 或HTML)

但這需要響應標頭包含字符串 「JSON」 。所以你要發送:

header('Content-type: application/json');

用的dataType這新增加的靈活性允許處理器應對多種類型的返回。

如果問題仍然存在,您需要提醒整個回覆alert(results);以查看實際返回的內容。

很多相似的答案在這裏。不知道是誰開始的,但毫無疑問入侵波蘭的人。

+0

感謝您的回答。如果我能參加波蘭評論,我會投票兩次。 – Matt 2010-04-27 03:29:52

+0

我想都是在同一時間創作的。 – Geoff 2010-04-27 21:46:29