JavaScript end:
Note: Be sure to set Xmlhttp.setrequestheader, otherwise the parameters passed to PHP will become null (line 38)
Highlights in line 31!
Copy Code code as follows:
<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 ("Your browser does not support 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= "Press me! "/>
<div id= "Show" ></div>
php Side "testjson.php":
(Note that the PHP file should be clean, the <?php?> label cannot have other tags outside, otherwise the Eval function cannot parse)
Highlights in line 6
Copy Code code as follows:
<?php
$res [' id '] = $_post[' id '];
$res [' name '] = "elar";
$res [' age '] = "21";
$response = "Hello this is response". $_post[' id '];
echo Json_encode ($res);
?>
Summarize:
JS to the PHP end to send data, with the Xmlhttp.send ("id=123");
PHP to send data to JS, with the Echo Json_encode ($res); (Note that the construction of variable $res should conform to the JSON specification)
JS to parse PHP sent to the JSON format of data, with var obj = eval (' + xmlhttp.responsetext + ') ');