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 +')');