2016-08-30 58 views
2

我試圖顯示我得到的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); 
     } 
+1

嘗試'JSON.stringify(data)' – depperm

+2

您收到一個對象。當使用alert()顯示時,它將被轉換爲一個字符串,默認爲'[object Object]'。試試'console.log()'來看看實際的對象。 – Sirko

+2

jQuery已經爲你解密了數據,你不需要使用'JSON.parse'。你看到'[object Object]'的原因是因爲你使用了'alert()'來查看它 - 這會強制所有類型都是字符串。改用'console.log' –

回答

1

,因爲你告訴你想要dataType:'json'的jQuery,ajax的函數解析JSON響應轉換成你的對象。您看到的結果對象應該是一個對象,其中的數據與來自服務器的JSON響應相匹配。如果您需要字符串版本,請嘗試JSON.stringify(),否則您可以直接使用該對象:data['results'][0]['DocId']

祝您好運!

0

這裏是您請求的示例:http://jsfiddle.net/5y5ea98n/

var echo = function(dataPass) { 
    $.ajax({ 
     type: "POST", 
     url: "/echo/json/", 
     data: dataPass, 
     cache: false, 
     success: function(json) { 
      alert(JSON.stringify(json)); 
     } 
    }); 
}; 

$('.list').live('click', function() { 
    $.get("http://www.json-generator.com/api/json/get/bQxORzxQGG?indent=2", function(data) { 
     var json = { 
      json: JSON.stringify(data), 
      delay: 1 
     }; 
     echo(json); 
    }); 
}); 
0

我嘗試了一些代碼涉及到這一點,它成功合作。

function ajaxToParseJson(){ 
AUI().use('aui-io-request', function(A){ 
    A.io.request('${jsonAjaxURL}', { 
      dataType:'json', 
      method: 'post', 
      data: { 
       execute: 'JsonLogic', 
       numberVal:'Pass Json String Here if needed from Screen' 
      }, 
      on: { 
        success: function() 
        { 
         var empName = this.get('responseData').name; 
         var id = this.get('responseData').id; 
         console.log("Name: "+empName); 
         console.log("Id: "+id); 
        /** Since return type of this function is bydefault Json it will return Json still if you want to check string below is the way**/ 
        var data = JSON.stringify(this.get('responseData')); 
        alert(data); 
        } 
       } 
     }); 

}); 

}

我有兩個字段ID,名稱的Employee類。