使用ajax和php在json中的语法错误

时间:2014-06-24 12:02:04

标签: json

这是完整的代码。错误似乎出现在jsonTesting.php页面中,其中包含变量文献,历史和喜剧。这让我知道这些变量没有被定义。这些变量应该是ajax的一个帖子。请帮助asap.here是我的php页面(jsonTesting.php):

<?php 
$library=
'{"closets":[
             {"id":"001","theme":"literature","shelves":
                                                           {
                                                            "books":    [{"id":"b1","genre":"english Literature"},
                                                                     {"id":"b2","genre":"arabic literature"},
                                                                     {"id":"b3","genre":"french literature"}  
                                                                        ]
                                                           }
             },
             {"id":"002","theme":"comedy","shelves":{
                                                      "books":[{"id":"b11","genre":"english comedy"},
                                                               {"id":"b22","genre":"arabic comedy"},
                                                               {"id":"b33","genre":"french comedy"}  
                                                              ]
                                                     }
             },
             {"id":"003","theme":"history","shelves":{
                                                       "books":[{"id":"b111","genre":"english history"},
                                                                {"id":"b222","genre":"arabic history"},
                                                                {"id":"b333","genre":"french history"}  
                                                                ]
                                                      }
             }
            ]

}';
//isset is used to make sure that we are reciving the post from the ajax
if(isset($_POST["literature"]))
$literature=$_POST["literature"];

if(isset($_POST["comedy"]))
$comedy=$_POST["comedy"];

if(isset($_POST["history"]))
$history=$_POST["history"];

$library = json_decode($library, true);

 $literatureBooks = $library['closets'][0]['shelves']['books'];
$comedyBooks= $library['closets'][1]['shelves']['books'];
$historyBooks= $library['closets'][2]['shelves']['books'];

if($literature)
{
 echo json_encode($literatureBooks);
 exit();
}

if ($comedy){

 echo json_encode($comedyBooks);
 exit();
}
if($history){
 echo json_encode($historyBooks);
 exit();
}
?>

1 个答案:

答案 0 :(得分:0)

试试这个,两者都是相似的但是我使用jquery实现每个coz 'each'将处理对象和json数组

$.ajax({
      url:"jsonTesting.php",
      data: {literature:'1'},
      type:'POST',
      success:function(data){
       if(data)
       {
        $.each(data,function(key,value){
            $("#books").append('<span>literature Books are'+value.id+'</span><br/>');
        }
      },
      error:function(){
      alert("Error in connection");
         }  
  });
});

如果这不起作用。请确保jsonTesting.php的json响应正确