1

我知道之前发布了很多 JSON 解析问题,但没有一个对我有帮助。

I am sending JSON back to my page from PHP via ajax. According to JSONLint.com I am using valid JSON.

My issue is everytime I go to access properties of my object they come back as undefined. I console.log the json object and it comes out fine. I am confused!

PHP

  $returnData[] = array("trainingAccess" => "$trainingAccess", 
    "destinationUrl" => "$destinationUrl", "errorMessage" => "$errorMessage");  

  echo json_encode($returnData);  

JS

      $.ajax({  
        type: "POST",  
        url: "submit_login.php",
        data: {
          userName: $("#userName").val(),
          password: $("#password").val()
        },
        success: function(data) {
          var obj = JSON.parse(data);

          console.log(obj);//Works
          alert(obj.destinationURL);//Doesn't work.
        }

Solution

I was making an array of arrays in PHP.

$returnData = array("trainingAccess" => "$trainingAccess", "destinationUrl" => "$destinationUrl", "errorMessage" => "$errorMessage");

4

2 回答 2

2

ajax方法将猜测结果的数据类型,如果它带有正确的内容类型,则可能会对其进行解析。

指定数据类型,以便您确定发生了什么,然后您知道数据已经为您解析:

  $.ajax({  
    type: "POST",  
    url: "submit_login.php",
    data: {
      userName: $("#userName").val(),
      password: $("#password").val()
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      alert(data[0].destinationUrl);
    }
于 2013-03-26T19:59:36.073 回答
2

尝试

alert(obj[0].destinationUrl);

大写小写问题。

编辑以显示实际解决方案供其他人查看...

于 2013-03-26T19:53:04.073 回答