PHP是怎么返回json格式的数据呢,json数据是一种特殊数据格式,可以实时也数据进行交互了,下面我来介绍PHP是怎么返回json格式的数据的吧。
我们常见一些网站在做ajax时返回JSON格式的数据:

php输出JSON格式
显然并非所愿。还是字符串,到底怎么实现?其实很简单,只要在php文件头部加入以下代码:
|  代码如下 | 
复制代码 | 
header('Content-type: text/json');  | 
示例代码:
|  代码如下 | 
复制代码 | 
< ?php header('Content-type: text/json'); $fruits = array (     "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),     "numbers" => array(1, 2, 3, 4, 5, 6),     "holes"   => array("first", 5 => "second", "third") ); echo json_encode($fruits); ?>  | 
先来看jquery
|  代码如下 | 
复制代码 | 
 $(function(){      $('#send').click(function() {           $.getJSON('http://blog.meituo.net/wp-content/uploads/php_return_json/test.js', 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);          })     }) })
  | 
你需要做的就是将数据存储为格式正确的 .json或者.js 文件。以下为示例所传送的json格式的数据
 
|  代码如下 | 
复制代码 | 
[   {     "username": "张三",     "content": "沙发."   },   {     "username": "李四",     "content": "板凳."   },   {     "username": "王五",     "content": "地板."   } ] | 

 本文地址:http://www.phprm.com/develop/45245.html
转载随意,但请附上文章地址:-)