jQuery通过Ajax向服务端发送JSON请求,使用方法$.getJSON非常方便简单。并且可以将服务端返回的数据进行解析,得到相应字段的内容,相比像HTML请求返回的一大串字符串那样处理方便快捷。
第一步:创建sql表
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(100) NOT NULL,
`sex` varchar(6) NOT NULL,
`tel` varchar(50) NOT NULL,
`email` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
第二步:写连接mysql的connect.php文件:
代码:
$host="localhost";
$db_user="root";
$db_pass="root";
$db_name="yctz";
$link=mysql_connect($host,$db_user,$db_pass);
mysql_select_db($db_name,$link);
?>
第三步:新建server.php
include_once("connect.php");
$action=$_GET['action'];
$id=intval($_GET['id']);
if($action=="getlink"){
$query=mysql_query("select * from user where id=$id");
$row=mysql_fetch_array($query);
$list=array("name"=>$row['username'],"sex"=>$row['sex'],"tel"=>$row['tel'],"email"=>$row['email']);
echo json_encode($list); }
?>
最后一步:新建test.html传递数值:
51模板集#userlist{margin:4px; height:42px} #userlist li{float:left; width:80px; line-height:42px; height:42px; font-size:14px; font-weight:bold} #info{clear:left; padding:6px; border:1px solid #b6d6e6; background:#e8f5fe} #info p{line-height:24px} #info p span{font-weight:bold}
$(function(){
$("#userlist a").bind("click",function(){
var hol=$(this).attr("rel");
var data="action=getlink&id="+hol;
$.getJSON("server.php",data,function(json){
$("#name").html(json.name);
$("#sex").html(json.sex);
$("#tel").html(json.tel);
$("#email").html(json.email);
});
});
});
姓名:
性别:
电话:
邮箱:
51模板集详细介绍jQuery通过Ajax向PHP服务端发送请求并返回JSON数据