PHP 与 js的通信(via ajax,json)
JavaScript端:
注意:一定要设置xmlHttp.setRequestHeader,否则传往PHP的参数会变成null(line 38)
亮点在line 31!
代码如下:
<script type="text/javascript">
function GetJson() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
//alert(xmlHttp.responseText);
var str = xmlHttp.responseText;
document.getElementById('show').innerHTML +=str;
//alert(str);
var obj = eval('('+ xmlHttp.responseText +')');
//var obj = eval(({"id":"123","name":"elar","age":"21"}));
alert(obj.name);
}
}
var data = "id=123";
xmlHttp.open("POST", "testJson.php", true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send("id=123");
}
</script>
<input type="button" onclick="GetJson()" value="按我!"/>
<hr />
<div id="show"></div>
PHP端【testJson.php】:
(注意,php文件要干净,<?php ?>标签的外部不能有其他标签,否则eval函数无法解析)
亮点在line 6
代码如下:
<?php
$res['id'] = $_POST['id'];
$res['name'] = "elar";
$res['age'] = "21";
$response = "hello this is response".$_POST['id'];
echo json_encode($res);
?>
总结:
js要往PHP端送数据,用的是xmlHttp.send("id=123");
PHP给js送数据,用的是echo json_encode($res);(要注意变量$res的构造应符合JSON的规范)
js要解析PHP送来的JSON格式的数据,用var obj = eval('('+ xmlHttp.responseText +')');