PHP如何返回json格式的數(shù)據(jù)給jquery
來源:程序員人生 發(fā)布時(shí)間:2014-01-15 01:40:56 閱讀次數(shù):3803次
json格式的數(shù)據(jù)是我們在應(yīng)用開發(fā)中一直會(huì)使用到的數(shù)據(jù),如與jquery打交到或與api打交都會(huì)使用到j(luò)son數(shù)據(jù),那么PHP如何返回json格式的數(shù)據(jù)給jquery呢,下面我來給各位同學(xué)介紹介紹.
在jquery中操作json數(shù)據(jù)我們直接 $.parseJSON(returnString ) 了
實(shí)例代碼如下:
- $(function(){
- $('#send').click(function() {
- $.getJSON('test.js', function(data) {
- $('#resText').emptyempty();
- 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);
- })
- })
- })
你需要做的就是將數(shù)據(jù)存儲(chǔ)為格式正確的 .json或者.js 文件.以下為示例所傳送的json格式的數(shù)據(jù)
實(shí)例代碼如下:
- [
- {
- "username": "張三",
- "content": "沙發(fā)."
- },
- {
- "username": "李四",
- "content": "板凳."
- },
- {
- "username": "王五",
- "content": "地板."
- }
- ]
上面講到到的json數(shù)據(jù)是固定了,我們用php如何返回json數(shù)據(jù)呢
php輸出JSON格式方法
頁面中加入header('Content-type: text/json');這個(gè)頭就是告知此文件輸出類型為 json,這種形式我們見的最多的是驗(yàn)證碼——php輸出驗(yàn)證圖片,有時(shí)php可以輸出css文件,js文件等做一些有趣的事情.好的,我們測試一下吧
實(shí)例代碼如下:
- < ?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);
- ?>
從數(shù)據(jù)庫讀取的數(shù)據(jù)生成json格式
實(shí)例代碼如下:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>第一php網(wǎng)提供的教程--將數(shù)據(jù)庫讀取的數(shù)據(jù)生成json格式</title>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"/></script>
- <script language=javascript>
- </script>
- </head>
- <body>
- <pre>
- <h1>請注意兩種方法生成的對象數(shù)組在結(jié)構(gòu)上的區(qū)別</h1>
- <?php
- echo '<h1>法一</h1>';
-
- $jarr=array('total'=>239,'row'=>array(
- array('code'=>'001','name'=>'中國','addr'=>'Address 11','col4'=>'col4 data'),
- array('code'=>'002','name'=>'Name 2','addr'=>'Address 12','col4'=>'col4 data'),
- )
- );
-
- $jobj=new stdclass();
-
- foreach($jarr as $key=>$value){
- $jobj->$key=$value;
- }
- print_r($jobj);
- echo '使用$jobj->row[0]['code']輸出數(shù)組元素:'.$jobj->row[0]['code'].'<br>';
- echo '編碼后的json字符串:'.json_encode($jobj).'<br>';
-
- echo '<hr>';
- echo '<h1>法二</h1>';
- echo '編碼后的json字符串:';
- echo $str=json_encode($jarr);
- echo '<br>';
- $arr=json_decode($str);
- print_r($arr);
- echo '使用$arr->row[0]->code輸出數(shù)組元素:'.$arr->row[0]->code;
- ?>
-
- </body>
- </html>
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)