get()方法实现:代码如下
DemoView.html(混合css,js代码使用)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AJAX实战之JSON的使用——JQ之get()实现</title>
<script type="text/javascript" src="jquery.min.js">
</script>
<style type="text/css">
#demo{display: inline-block;
padding: 4px;
background: #cecece;
color: white;
cursor: pointer;}
#demo:hover{background: #990000;
font-weight: bold;}
</style>
</head>
<body>
<div>
<ul id="list">
<li>hello world</li>
</ul>
<span id="demo">StartDemo</span>
</div>
<script type="text/javascript">
$("document").ready(function(){
$("#demo").click(function(){
$.get("DATA_ORIGIN.php", function(data, status){
$("#list li").remove();
json_data = JSON.parse(data);
$.each(json_data, function(i, v){
temp = "";
$.each(v, function(K, C){
temp += K+":"+C;
});
text = $("<li></li>").text(temp);
$("#list").append(text);
});
});
});
});
</script>
</body>
</html>
DATA_ORINGIN.php (数据来源文件)
$mysql = new mysqli("localhost", "root", "密码", "数据库名");
$sql = "select * from json_data";
if(mysqli_connect_error()){
die(error_reporting());
}
$result = $mysql->query($sql);
$data = array();
if($result->num_rows > 0){
$i = 0;
while($row = $result->fetch_assoc()){
$data[$i]['search_key'] = $row['search_key'];
$data[$i]['url'] = $row['url'];
$i++;
}
}
$json = json_encode($data);
echo $json;
另外还需要引用的jquery.min.js文件和对应的数据库
文件清单为:DATA_ORIGIN.php, DemoView.html,jquery.min.js(该文件可去官网下载)
效果演示:
post()方法实现
DemoView.html(混合css,js代码使用)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AJAX实战之JSON的使用——JQ之post()实现</title>
<script type="text/javascript" src="jquery.min.js">
</script>
<style type="text/css">
#demo{display: inline-block;
padding: 4px;
background: #cecece;
color: white;
cursor: pointer;}
#demo:hover{background: #990000;
font-weight: bold;}
</style>
</head>
<body>
<div>
<h1 id="h1">hello world</h1>
<span id="demo">DemoStart</span>
</div>
<script type="text/javascript">
$("document").ready(function(){
$("#demo").click(function(){
$.post("DATA_ORIGIN.php", {search_key:"json_01"}, function(data, status){
json_data = JSON.parse(data);
$.each(json_data, function(i, v){
temp = "";
$.each(v, function(K, C){
temp += K+":"+C+"\n";
})
$("#h1").html(temp);
})
})
})
})
</script>
</body>
</html>
DATA_ORIGIN.php (数据来源文件)
<?php
if(!isset($query)){
$query = isset($_POST['search_key']) ? htmlspecialchars($_POST['search_key']) : '';
}
$mysql = new mysqli("localhost", "root", "密码", "数据库名");
$sql = "select * from json_data where search_key like '%$query%'";
if(mysqli_connect_error()){
die(error_reporting());
}
$result = $mysql->query($sql);
$data = array();
if($result->num_rows > 0){
$i = 0;
while($row = $result->fetch_assoc()){
$data[$i]['search_key'] = $row['search_key'];
$data[$i]['url'] = $row['url'];
$i++;
}
}
$json = json_encode($data);
echo $json;
?>
同样还需要引用的jquery.min.js文件和对应的数据库
文件清单为:DATA_ORIGIN.php, DemoView.html,jquery.min.js(该文件可去官网下载)
效果演示:
以上就完成了 AJAX实战之JSON使用 (JQ中运用post()和ge()方法分别实现)