jQuery+Ajax+js要求json花样数据并衬着到html页面

json花样的数据文件有两种体式格局
一种是xxx.json文件
一种是xxx.php文件
前者是json花样的文件
后者是输出json花样的文件
前者是当地的文件
后者是猎取数据库的数据再输出成json花样的php文件
先说前者
比方有一个json花样的文件
data.json

[  
    {  
    "id":"001",  
    "title":"百度",  
    "url":"http://www.baidu.com"  
    },  
    {  
    "id":"002",  
    "title":"阿里",  
    "url":"www.alibaba.com"  
    },  
    {  
    "id":"003",  
    "title":"腾讯",  
    "url":"www.qq.com"  
    }  
]  

经由过程ajax.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>

到这里,经由过程ajax.html吧data.json数据给衬着到页面了。

下面将以下从数据库猎取数据而且衬着到html页面
比方命名为api.php,这个页面主如果查询数据库

<?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.php

<?php  
//设置文件 - BY TANKING  
//下面是衔接数据库主机、用户名、暗码、数据库名、表名  
$host="localhost";  
$username="root";  
$password="root";  
$db="list";  
$restb="reslist";  
?>  

接见api.php会直接输出前者的json花样数据
所以跟前者一样,只是一个是在数据库猎取,一个是在当地猎取
我们要注意这段,api.php一定要声明这是一个json花样的数据,不然没法剖析。
header(“content-type:application/json”);

结果:

《jQuery+Ajax+js要求json花样数据并衬着到html页面》

    原文作者:TANKING
    原文地址: https://segmentfault.com/a/1190000012914866
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞