有关ajax处理返回的json格式数据详细方法讲解

以用户注册为例:

register.php

<html>
<head>
<title>用户注册</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
 
	//创建ajax引擎
	function getXmlHttpObject(){
		
		var xmlHttpRequest;
		//不同的浏览器获取对象xmlhttprequest 对象方法不一样
		if(window.ActiveXObject){
			
			xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
			
		}else{
 
			xmlHttpRequest=new XMLHttpRequest();
		}
 
		return xmlHttpRequest;
 
	}
	var myXmlHttpRequest="";
 
	//验证用户名是否存在
	function checkName(){
		
		myXmlHttpRequest=getXmlHttpObject();
 
		//怎么判断创建ok
		if(myXmlHttpRequest){
			
			//通过myXmlHttpRequest对象发送请求到服务器的某个页面
			//第一个参数表示请求的方式, "get" / "post"
			//第二个参数指定url,对哪个页面发出ajax请求(本质仍然是http请求)
			//第三个参数表示 true表示使用异步机制,如果false表示不使用异步
			var url="regisgerProcess.php";
			//这个是要发送的数据
			var data="username="+$('username').value;
			//打开请求.
			myXmlHttpRequest.open("post",url,true);
			//还有一句话,这句话必须.
			myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			//指定回调函数.chuli是函数名
			myXmlHttpRequest.onreadystatechange=chuli;
 
			//真的发送请求,如果是get请求则填入 null即可
			//如果是post请求,则填入实际的数据
			myXmlHttpRequest.send(data); 
 
 
		}
	}
 
	//回调函数
	function chuli(){
		
		//window.alert("处理函数被调回"+myXmlHttpRequest.readyState);
		//我要取出从registerPro.php页面返回的数据
		if(myXmlHttpRequest.readyState==4){
			
			//取出值,根据返回信息的格式定.text
			//window.alert("服务器返回"+myXmlHttpRequest.responseText);
 
			//$('myres').value=myXmlHttpRequest.responseText;
 
			//看看如果取出 xml格式数据
			//window.alert(myXmlHttpRequest.responseXML);
		
			//取出text或json数据用下面方式:获取mes节点
			var mes=myXmlHttpRequest.responseText;
			window.alert(mes);
			//使用 eval 函数将 mes字符串转换为对应的对象,注意eval函数格式如下:
			mes_obj = eval ("(" + mes + ")");
			window.alert(mes_obj.res);
			$('myres').value=mes_obj.res;
		}
	}
 
	//这里我们写一个函数
	function $(id){
		return document.getElementById(id);
	}
</script>
</head>
<body>
	<form action="regisgerProcess.php" method="post">
 用户名字:<input type="text" name="username1" id="username"><input type="button" onclick="checkName();" value="验证用户名">
 <input style="border-width: 0;color: red" type="text" id="myres">
 <br/>
 用户密码:<input type="password" name="password"><br>
 电子邮件:<input type="text" name="email"><br/>
 <input type="submit" value="用户注册">
 </form>
  <form action="???" method="post">
 用户名字:<input type="text" name="username2" >
 
 <br/>
 用户密码:<input type="password" name="password"><br>
 电子邮件:<input type="text" name="email"><br/>
 <input type="submit" value="用户注册">
 </form>
 
</body>
</html>

regisgerProcess.php:

<?php
	//这里两句话很重要,第一讲话告诉浏览器返回的数据格式,若返回xml格式数据,此处写header("Content-Type: text/xmla;set=utf-8"); ,
	//若返回tex或json数据,此处填写header("Content-Type: text/html;charset=utf-8");
	header("Content-Type: text/html;charset=utf-8");
	//告诉浏览器不要缓存数据
	header("Cache-Control: no-cache");
 
	//接收数据(这里要和请求方式对于 _POST 还是 _GET)
	$username=$_POST['username'];
 
	//这里我们看看如何处理格式是json
	$info="";
	if($username=="shunping"){
		$info.='{"res":"用户名可用"}';//注意,这里数据是返回给请求的页面.
	}else{
		$info.='{"res":"用户名不可用","id":"001"}';
	}
	echo $info;
?>

json数据详解:

1、json的格式如下 :

“{属性名:属性值,属性名:属性值,…. }”

因为json数据是原生态数据,因此这种数据格式很稳定,而且描述能力强,我们建议大家使用json格式

2、 json数据格式的扩展

如果服务器返回的json 是多组数据,则格式应当如下:

$info=”[{“属性名”:”属性值”,…},{“属性名”:”属性值”,…},….]”;

在xmlhttprequest对象接收到json数据后,应当这样处理

//转成对象数组

varreses=eval(“(“+xmlHttpRequest.responseText+”)”);

//通过reses可以取得你希望的任何一个值

reses[?].属性名

3、 更加复杂的json数据格式

<scriptlanguage="JavaScript">
  var people ={
   "programmers":
    [
    {"firstName":"Brett", "email": "brett@newInstance.com" },
    {"firstName":"Jason", "email": "jason@servlets.com" }
    ],
   "writer":
      [
       {"writer":"宋江","age":"50"},
       {"writer":"吴用","age":"30"}
      ],
      "sex":"男"     
};
window.alert(people.programmers[0].firstName);
window.alert(people.programmers[1].email);
 
window.alert(people.writer[1].writer);
window.alert(people.sex);
 </script>

4、当一个ajax请求到服务器,服务器可以根据需求返回 三种格式的数据,那么我们应当选择哪一个?

a. 如果你的项目经理没有特殊的要求,建议使用json

b. 若应用程序不需要与其他应用程序共享数据的时候, 使用 HTML 片段来返回数据时最简单的

c. 如果数据需要重用, JSON 文件是个不错的选择, 其在性能和文件大小方面有优势

d. 当远程应用程序未知时, XML 文档是首选, 因为 XML 是 web 服务领域的 “世界语”

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容