2016-08-30 57 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类。