json格式的數據文件有兩種方式
一種是xxx.json文件
一種是xxx.php文件
前者是json格式的文件
後者是輸出json格式的文件
前者是本地的文件
後者是獲取數據庫的數據再輸出成json格式的php文件
先說前者
例若有一個json格式的文件
data.jsonphp
[ { "id":"001", "title":"百度", "url":"http://www.baidu.com" }, { "id":"002", "title":"阿里", "url":"www.alibaba.com" }, { "id":"003", "title":"騰訊", "url":"www.qq.com" } ]
經過ajax.html獲取數據html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax請求json數據</title> </head> <body> <div id="test"></div> <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script> <script> $(function(){ $.ajax({ //請求方式 type:"GET", //文件位置 url:"data.json", //返回數據格式爲json,也能夠是其餘格式如 dataType: "json", //請求成功後要執行的函數,拼接html success: function(data){ var str="<ul>"; $.each(data,function(i,n){ str+="<li>"+"ID:"+n.id+"</li>"; str+="<li>"+"標題:"+n.title+"</li>"; str+="<li>"+"地址:"+n.url+"</li>"; }); str+="</ul>"; $("div").append(str); } }); }); </script> </body> </html>
html頁面引入了
<script src="https://code.jquery.com/jquer...;></script>mysql
到這裏,經過ajax.html吧data.json數據給渲染到頁面了。jquery
下面將如下從數據庫獲取數據而且渲染到html頁面
例如命名爲api.php,這個頁面主要是查詢數據庫ajax
<?php header("content-type:application/json"); //獲取數據庫配置 require_once("config.php"); //鏈接數據庫 $con = mysql_connect($host,$username,$password); if (!$con) { die('鏈接數據庫失敗,失敗緣由:' . mysql_error()); } //設置數據庫字符集 mysql_query("SET NAMES UTF8"); //查詢數據庫 mysql_select_db($db, $con); //獲取最新的10條數據 $result = mysql_query("SELECT id,resname,imgurl,resint,resurl,pageview FROM $restb ORDER BY id DESC LIMIT 0,10"); $results = array(); while ($row = mysql_fetch_assoc($result)) { $results[] = $row; } // 將數組轉成json格式 echo json_encode($results); // 關閉鏈接 mysql_free_result($result); mysql_close($link); echo $json; ?>
由於涉及到連接數據庫,我把數據庫地址、帳號、密碼、數據庫名、表名都寫到了一個config.php裏面直接在api.php引入。
config.phpsql
<?php //配置文件 - BY TANKING //下面是鏈接數據庫主機、用戶名、密碼、數據庫名、表名 $host="localhost"; $username="root"; $password="root"; $db="list"; $restb="reslist"; ?>
訪問api.php會直接輸出前者的json格式數據
因此跟前者同樣,只是一個是在數據庫獲取,一個是在本地獲取
咱們要注意這段,api.php必定要聲明這是一個json格式的數據,不然沒法解析。
header("content-type:application/json");數據庫
效果:json