我試圖顯示我得到的json並解析它在ajax的成功函數中。解析json使用ajax成功函數
我到目前爲止有:
阿賈克斯:
data = "Title=" + $("#Title").val() + "&geography=" + $("#geography").val();
alert(data);
url= "/portal/getResults.php";
$.ajax({
url: url,
type: "POST",
//pass the data
data: data,
dataType: 'json',
cache: false,
//success
success: function(data) {
alert(data);
}
});
getResults.php(JSON輸出):
{
"results": [
{
"DocId": 2204,
"Title": "Lorem ipsum dolor sit amet, consectetur",
"Locations": [
{
"State": "New York",
"City": ""
},
{
"State": "New York",
"City": "New York City"
}
],
"Topics": [
3,
7,
11
],
"PublicationYear": "2011",
"Organization": "New Yorks Times",
"WebLocation": "www.google.com",
"Description": "Lorem Ipsum"
}
],
"TotalMatches": 1
}
我希望得到的結果數據是從json的getResults.php,但是我得到[object Object]。
我也曾嘗試下面的代碼,但沒有得到響應:
success: function(data) {
var json1 = JSON.parse(data);
alert(json1);
}
嘗試'JSON.stringify(data)' – depperm
您收到一個對象。當使用alert()顯示時,它將被轉換爲一個字符串,默認爲'[object Object]'。試試'console.log()'來看看實際的對象。 – Sirko
jQuery已經爲你解密了數據,你不需要使用'JSON.parse'。你看到'[object Object]'的原因是因爲你使用了'alert()'來查看它 - 這會強制所有類型都是字符串。改用'console.log' –