<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax json test</title>
<script language="javascript" src="js/jquery-1.8.1.js"/></script>
</head>
<body style="font-family:Arial;line-height:150%">
<h1>Ajax利用JSON进行前后台交互</h1>
<a href="javascript:getAllUsers();">获取所有用户信息</a> <br/>
<!-- 用于显示返回结果 -->
<div id="users"></div>
</body>
</html>
<script type="text/javascript">
function getJson(RequestData,URL){
var reJson;
$.ajax({
type:'POST',
url:URL,
data:RequestData,
async:false,//为了简便,设置为同步操作
cache: false,
success:function(responseData){
reJson=responseData;
}
});
return reJson;
}
function getAllUsers(){
var url = "json.PHP";
var request = 'action=get_all_users';
//从后台获取并解析,由于上面封装ajax采用的是同步返回,
//所以这样操作能成功获取返回数据
var json = getJson(request,url);
var users = eval('('+ json +')');//将字符串转化为json对象
var usersHtml = '<br/><span style="color:red;">Ajax返回的JSON字符串:</span><br/>'
+ json + '<br/><br/><span style="color:red;">解析出来的结果为:</span><br/>';
for(var i=0;i<users.length;++i){
usersHtml += 'userId = ' + users[i].userId + '<br/>'
+ 'userName = ' + users[i].userName + '<br/>';
}
//把构造的HTML利用jQuery动态显示到页面
$('#users').empty().html(usersHtml);
}
</script>
<?PHP //接受请求参数并根据参数选择操作if(isset($_POST['action'])&&$_POST['action']!=""){ switch($_POST['action']){ case 'get_all_users': getAllUsers(); break; default: }}//处理请求:以JSON格式返回所有用户信息function getAllUsers(){ $users = array( array("userId"=>1,"userName"=>"Raysmond"),array("userId"=>2,"userName"=>"雷建坤"),array("userId"=>3,"userName"=>"Rita") ); echo json_encode($users);}?>
原文链接:https://www.f2er.com/ajax/162192.html