本文实例讲述了php+ajax处理xml与json格式数据的方法。分享给大家供大家参考,具体如下:
一、ajax如何处理xml数据格式
register.php
只需修改上一篇《php+ajax无刷新验证用户名操作》中chuli函数部分
functionchuli(){
// window.alert("cuhli函数被调用"+myxmlhttprequest.readystate);
//我要取出从register.php返回的数据
if(myxmlhttprequest.readystate==4){
//------------看看如何取出xml数据--------
//获取mes节点
var mes=myxmlhttprequest.responsexml.getelementsbytagname("mes");
//取出mes节点值
var mes_value=mes[0].childnodes[0].nodevalue;
$("myres").value=mes_value;
}
}
process.php 代码
//第一讲话告诉浏览器返回的数据是xml格式
header("content-type:text/xml;charset=utf-8");
//告诉浏览器不要缓存数据
header("cache-control:no-cache");
//接收数据(这里要和请求方式对于 _post 还是 _get)
$username=$_post['username'];
//这里我们看看如何处理格式是xml
$info="";
if($username=="李四"){
$info.="用户名不可以用,对不起";//注意,这里数据是返回给请求的页面.
}else{
$info.="用户名可以用,恭喜";
}
echo $info;
?>
二、ajax如何处理json数据格式
json格式介绍
① json的格式如下 :
"{属性名:属性值,属性名:属性值,.... }"
因为json数据是原生态数据,因此这种数据格式很稳定,而且描述能力强,我们建议大家使用json格式
② json数据格式的扩展
如果服务器返回的json 是多组数据,则格式应当如下:
$info="[{"属性名":"属性值",...},{"属性名":"属性值",...},....]";
在xmlhttprequest对象接收到json数据后,应当这样处理
//转成对象数组
varreses=eval("("+xmlhttprequest.responsetext+")");
//通过reses可以取得你希望的任何一个值
reses[?].属性名
③ 更加复杂的json数据格式
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);
register.php 部分中chuli函数
function chuli(){
if(myxmlhttprequest.readystate==4){
//------------看看如何取出json数据--------
var mes= myxmlhttprequest.responsetext;
//使用evla函数将mes转换成相应的对象
var mes_obj=eval("("+mes+")");
$("myres").value=mes_obj.res;
}
}
process.php 代码
header("content-type: text/html;charset=utf-8");
//告诉浏览器不要缓存数据
header("cache-control: no-cache");
$info="";
if($username=="1"){
$info='{"res":"该用户不可用"}';
}
else{
//$info是一个json数据格式的字串
$info='{"res":"恭喜,用户名可用"}';
}
echo $info;
?>
希望本文所述对大家php程序设计有所帮助。