码迷,mamicode.com
首页 > Web开发 > 详细

json

时间:2015-05-26 21:10:07      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

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

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);
?>

json

标签:

原文地址:http://www.cnblogs.com/pcd12321/p/4531489.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!