如何使用jquery获取json数据并在div中显示

时间:2012-01-09 01:16:07

标签: php json jquery

让我们说..我的控制器中有以下脚本:

 $result= array("Name"=>Charlie Sheen, "Age"=>30); 
 echo josn_encode($result);

在我的视图文件中,我有以下java脚本。现在,请你告诉我在下面脚本的成功函数中要写什么,以便在body标签内的两个不同的div中显示“Name”和“Age”?我已经找到了一些这方面的教程,但所有这些对我来说都很困惑。能帮助你吗?

先谢谢:)

<script  type="text/javascript">
 $(function(){ // added

     $('a.read').click(function(){
            var a_href = $(this).attr('href'); 

     $.ajax({

     type: "POST",
     url: "<?php echo base_url(); ?>batch/get_info",
     data: "id="+a_href,
     success: function(server_response){
                                                  //What exactly to write here
                                         }                                      
                                            }); //$.ajax ends here                          
                                                return false    

    });//.click function ends here

  }); // function ends here                        

 </script>  

2 个答案:

答案 0 :(得分:1)

确保正确拼写json_encode功能。

你的HTML应该是这样的:

<head>

<script  type="text/javascript">
$(function(){ // added

 $('a.read').click(function(){
     var a_href = $(this).attr('href'); 

     $.ajax({

        dataType : 'json', //You need to declare data type

        type: "POST",
        url: "<?php echo base_url(); ?>batch/get_info",
        data: "id="+a_href,
        success: function(server_response){
           $( '#name' ).text( server_response.Name );
           $( '#age' ).text( server_response.Age);
        }                                      
      }); //$.ajax ends here                          
      return false    

   });//.click function ends here

}); // function ends here                        

</script>  

</head>
<body>

   <div id='name'></div>
   <div id='age'></div>

</body>

答案 1 :(得分:0)

首先,您应该设置dataType。它应该具有值'json'。至于访问它,您只需像访问任何其他JavaScript对象一样访问它:

<script type="text/javascript">
$(function() {
     $('a.read').click(function() {
         var a_href = $(this).attr('href'); 

         $.ajax({
             type: "POST",
             url: "<?php echo base_url(); ?>batch/get_info",
             data: "id=" + a_href,
             dataType: 'json',
             success: function(result) {
                alert(result.Name); // Charlie Sheen 
             }                                      
         });

         return false;
    });
});
</script>