2015-07-21 103 views
0

是我得到的错误是这样的,如果我使用的dataType:“JSON”:无法显示JSON对象

Uncaught TypeError: Cannot read property 'length' of undefined

如果我使用dataType:'html'话,我可以看到数组传递形式的PHP页面在控制台像这样:

[{ 
    "type": ["4 wheeler", "flying car", "test type"], 
    "maker": ["Honda", "Audi", "test car"], 
    "rate": [ 
     ["0", "78"], 
     ["0", "56"], 
     ["0", "34"], 
     ["2", "78"], 
     ["2", "56"], 
     ["2", "34"], 
     ["1", "89"], 
     ["1", "7"], 
     ["1", "56"] 
    ] 
}] 

在我的php页面,这是我如何传递多维数组。

$json=array(); 
array_push($json,array("type"=>$carType,"maker"=>$carMaker,"rate"=>$selectRate)); 
echo json_encode($json); 

这是我的错吗? AM我没有从这个页面传入JSON对象?如何在成功函数中通过jquery访问每个数组中的每个元素?阿贾克斯

$("#submit").on("click",function() 
    { 

      $("#set_setting").submit(function(){    

      data = $(this).serialize() 
      $.ajax({ 
       type: "POST", 
       dataType: "html", 
       url: "submit_setting.php", //Relative or absolute path to response.php file 
       data: data, 
       success: function(data) { 
        //alert(JSON.stringify(data)); 
        //data=JSON.stringify(data); 
        console.log(data); 
        //hide the form 
        $("#set_setting").slideUp("slow"); 

        //show the result 


         $.each(data.type, function(index, value){ 
          console.log(value); 
         }); 
       } 

      }); 
      return false; 

      }); 

     }); 
+0

您提供的错误在您的代码中似乎不匹配。你能分享你的整个代码吗? – LinkinTED

+0

@LinkinTED我用整个代码更新了我的帖子 – 112233

+0

控制台说什么?或无?然后尝试添加错误事件,并查看记录了哪些错误。 – LinkinTED

回答

0

您发送跨阵列以纯文本

整个代码。它需要被序列化为JSON。我不知道php中的语法,你需要查看它。您可以通过从Postman或Fiddler进行调用来测试,您将看到响应类型。

0

你需要添加像下面的关键我想!

$json['data']=array(); 
$json['data'] = array("type"=>$carType,"maker"=>$carMaker,"rate"=>$selectRate); 
echo json_encode($json); 

请参阅this链接访问JSON对象,看看导致浏览器控制台

+0

我试过了,但它不会更改或输出任何东西 – 112233

0

你已经序列化的阵列中JSON,所以你不能访问HTML数据类型的数组。您需要将数据返回为html,以便在js中以html格式访问它。

最佳做法是使用print_r而不是echo来打印数组。 echo不能在php中打印数组元素。

<?php print_r($json) ?> 

然后使用foreach循环来循环元素。

+0

这可以在php页面中工作。但我有gproblem传递这个数组通过ajax作为json和显示在另一个页面for循环 – 112233

+0

看到我更新的帖子 –