json

一.通过现有的数据直接返回

demo.html

<script type="text/javascript">
   $(function(){
        $('#send').click(function() {
             $.getJSON('test.json', function(data) {
                 $('#resText').empty();
      var html = '';
      $.each( data  , function(commentIndex, comment) {
       html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
      })
     $('#resText').html(html);
            })
       })
   })
</script>//方式一

<script type="text/javascript">
   $(function(){
        $('#send').click(function() {
            $.ajax({
     type: "GET",
     url: "test.json",
     dataType: "json",
     success : function(data){
            $('#resText').empty();
       var html = '';
       $.each( data  , function(commentIndex, comment) {
        html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
       })
      $('#resText').html(html);
     }
   });
        });
   })
</script>//方式二

<body>
 <br/>
 <p>
  <input type="button" id="send" value="加载"/>
 </p>
<div  class="comment">已有评论:</div>
 <div id="resText" >
 </div>
</body>

test.json

[
  {
    "username": "张三",
    "content": "沙发."
  },
  {
    "username": "李四",
    "content": "板凳."
  },
  {
    "username": "王五",
    "content": "地板."
  }
]

二.后端从前端获得数据再返回前端

<script type="text/javascript">
 $(function(){
    $("#send").click(function(){
   $.get("get3.php", {
      username :  $("#username").val() ,
      content :  $("#content").val() 
     }, function (data, textStatus){
         var username = data.username;
      var content = data.content;
         var txtHtml = "<div class='comment'><h6>"+username+":</h6><p class='para'>"+content+"</p></div>";
                        $("#resText").html(txtHtml); // 把返回的数据添加到页面上
     },"json");
     return false;
    })
 })
</script>

<body>
<form id="form1" action="#">
<p>评论:</p>
 <p>姓名: <input type="text" name="username" id="username" /></p>
 <p>内容: <textarea name="content" id="content"  rows="2" cols="20"></textarea></p>
 <p><input type="button" id="send" value="提交"/></p>
</form>
<div  class='comment'>已有评论:</div>
<div id="resText" >
</div>
</body>

get3.php

<?php
header("Content-Type:text/html; charset=utf-8");
$arr = array('username'=>$_GET['username'],'content'=>$_GET['content']);
echo json_encode($arr);
?>

posted @ 2015-05-26 19:23  PLDaily  阅读(112)  评论(0编辑  收藏  举报