2013-07-24 50 views
0

代码:解析JSON在Ajax中,错误

$.ajax({ 
     type: "POST", 
     url: "API URL", 
     data: JSON.stringify(User), 
     dataType : "json", 
     success: function(apiResponse) { 
      var session = apiResponse.sessionId; 
      console.log ("Session : "+ session); 

      $.ajax({ 
       type: "GET", 
       url: "ANOTHER URL", 
       dataType : "jsonp", 
       contentType: "jsonp", 
       success: function(apiResponse) { 
        console.log (apiResponse); 
        jQuery.each(apiResponse,function(){ 
         console.log (apiResponse); 
              }); 
        }, 
       error: function(apiResponse) { 
        alert("error : " +apiResponse); 
       } 
      }); 
     }, 
     error: function(apiResponse) { 
      alert("error : " +apiResponse); 
     } 

===========

PHP代码返回JSON数据

<?php 

$jsonp = false; 
if (isset($_GET[ 'callback' ])) { 
    $_GET[ 'callback' ] = strip_tags($_GET[ 'callback' ]); 
    $jsonp    = true; 
    $pre = $_GET[ 'callback' ] . '('; 
    $post = ');'; 
    } //isset($_GET[ 'callback' ]) 

/* Encode JSON, and if jsonp is true, then ouput with the callback 
** function; if not - just output JSON. */ 
$json = json_encode('{"top cat1":[{"id":"cat1", "name":"product1"}, {"id":"cat2", "name":"product 2"}], "top cat2":[{"id":"cat3", "name":"product 3"}, {"id":"cat4", "name":"product 4"}]}'); 
print(($jsonp) ? $pre . $json . $post : $json); 

另一个URL返回以下数据

{"top cat1":[{"id":"cat1", "name":"product1"}, {"id":"cat2", "name":"product 2"}], "top cat2":[{"id":"cat3", "name":"product 3"}, {"id":"cat4", "name":"product 4"}]} 

================ 现在,我得到以下错误(也提的console.log RESP)

Session : 67a47816-5a03-44f9-ab24-01e1e8d4aad1 

    {"top cat1":[{"id":"cat1", "name":"product1"}, {"id":"cat2", "name":"product 2"}], "top cat2":[{"id":"cat3", "name":"product 3"}, {"id":"cat4", "name":"product 4"}]} 

    TypeError: invalid 'in' operand e 
    [Break On This Error]  

    ...ute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r... 

=======================

什么我想要 1.解析Json响应。 “Top Cat1”会列出它下面的标题列表。

我在做什么错。

+0

你告诉jQuery的期待JSONP,但您发布的数据JSON,而不是JSONP。 –

+0

增加了PHP代码。请看上面的 –

回答

0

为什么在一个已经被json编码的字符串中使用函数json_encode?

$json = json_encode('{"top cat1":[{"id":"cat1", "name":"product1"}, {"id":"cat2", "name":"product 2"}], "top cat2":[{"id":"cat3", "name":"product 3"}, {"id":"cat4", "name":"product 4"}]}'); 

通常你应该使用:如果你有类似的东西

$json = '"top cat1":[{"id":"cat1", "name":"product1"}, {"id":"cat2", "name":"product 2"}], "top cat2":[{"id":"cat3", "name":"product 3"}, {"id":"cat4", "name":"product 4"}]}'; 

json_encode时,应使用:

$arrayTemp = array("top cat1"=>array(array("id"=>"cat1","name"=>"product1"),array("id"=>"cat2","name"=>"product 2")),"top cat2"=>array(array("id"=>"cat3","name"=>"product 3"),array("id"=>"cat4","name"=>"product 4"))); 

$json = json_encode($arrayTemp); 
+0

hmmmm。它仍然没有解决JS方的错误:( –

+0

请问您可以将请求的完整结果粘贴到php页面,当使用浏览器url中的简单“get”调用它时。 – ElLocoCocoLoco