处理ajax返回数据类型
ajax返回数据类型:纯文本格式、xml、json
如果只获取简单的字符串可以采用纯文本格式。
如果返回的数据类型比较复杂,则采用xml或者json。
采用XML来处理数据
服务器返回代码如下:
<?PHP
header("Content-Type:text/xml;charset=utf-8");
header("Cache-Control: no-cache");
$username = $_POST['username'];
if($username == 'chuizhi'){
$info= "<res><mes>用户名不可用</mes></res>";
}
else {
$info="<res><mes>用户名可以用</mes></res>";
}
echo $info;
?>
header("Content-Type:text/xml;charset=utf-8");
header("Cache-Control: no-cache");
$username = $_POST['username'];
if($username == 'chuizhi'){
$info= "<res><mes>用户名不可用</mes></res>";
}
else {
$info="<res><mes>用户名可以用</mes></res>";
}
echo $info;
?>
注意红色部分是text/xml格式,这样浏览器才会建立DOM对象(渲染DOM树),若为text/html格式,则浏览器只会以文本方式来存储数据
function callBack(xmlHttp){
if (xmlHttp.readyState==4 && xmlHttp.status == 200){
//获取DOM对象
var xmlDoc = xmlHttp.responseXML;
//获取mes节点,可能存在多个mes节点
var mes = xmlDoc.getElementsByTagName("mes");
if (xmlHttp.readyState==4 && xmlHttp.status == 200){
//获取DOM对象
var xmlDoc = xmlHttp.responseXML;
//获取mes节点,可能存在多个mes节点
var mes = xmlDoc.getElementsByTagName("mes");
//<mes>content</mes>
$('myres').value = mes[0].childNodes[0].nodeValue;
}
}
}
}
json数据格式
xml以树形格式存储,json数据以键值对的形式存储
基本格式:
var people ={"Name": "Bob","Tel":"123456789","email": "Bob@163.com" };
数组形式:
var people =[{"Name": "Bob","Tel":"123456798","email": "Bob@163.com" },
{"Name": "Rose","Tel":"123854697","email": "Rose@126.com" }
];
混合形式1:
{"Name": "Rose","Tel":"123854697","email": "Rose@126.com" }
];
混合形式1:
var people ={"programmers":[
{"Name": "Bob","Tel":"1668975656","email": "brett@newInstance.com" },
{"Name": "Jason"," Tel":"13851685142","email": "jason@servlets.com" }
]
};
访问方式:people.programmers[0].Name
{"Name": "Bob","Tel":"1668975656","email": "brett@newInstance.com" },
{"Name": "Jason"," Tel":"13851685142","email": "jason@servlets.com" }
]
};
访问方式:people.programmers[0].Name
混合方式2:
var people ={"username":"mary","age":"20","info":{"tel":"1234566","celltelphone":788666},
"address":[
{"city":"beijing","code":"1000022"},
{"city":"shanghai","code":"2210444"}
]
};
"address":[
{"city":"beijing","code":"1000022"},
{"city":"shanghai","code":"2210444"}
]
};
访问方式:
people.username
people.info.tel
people.address[0].city
people.username
people.info.tel
people.address[0].city
用JSON获取数据
function callBack(xmlHttp){
if (xmlHttp.readyState==4 && xmlHttp.status == 200){
//获取字符串
var resText = xmlHttp.responseText;
//将其转换为JSON数据格式
var resObj = eval("(" + resText +")");
//通过键值对的方式来访问
alert(resObj.mes);
alert(resObj.id);
alert(resObj.date);
$('myres').value = resObj.mes;
}
}
if (xmlHttp.readyState==4 && xmlHttp.status == 200){
//获取字符串
var resText = xmlHttp.responseText;
//将其转换为JSON数据格式
var resObj = eval("(" + resText +")");
//通过键值对的方式来访问
alert(resObj.mes);
alert(resObj.id);
alert(resObj.date);
$('myres').value = resObj.mes;
}
}
后端要说明以text/html方式来发送数据
发送的数据虽然是字符串,但需采用JSON数据格式
原文链接:https://www.f2er.com/ajax/162636.html