JavaScript:
Note: Make sure to set xmlHttp. setRequestHeader. Otherwise, the parameter passed to PHP will become null (line 38)
The highlights are in line 31!
Copy codeThe Code is 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! "/>
<Hr/>
<Div id = "show"> </div>
PHP end [testJson. php ]:
(Note: The php file should be clean, <? Php?> There cannot be other labels outside the tag, otherwise the eval function cannot PARSE)
Highlights in line 6
Copy codeThe Code is as follows:
<? Php
$ Res ['id'] = $ _ POST ['id'];
$ Res ['name'] = "elar ";
$ Res ['age'] = "21 ";
$ Response = "hello this is response". $ _ POST ['id'];
Echo json_encode ($ res );
?>
Summary:
Js uses xmlHttp. send ("id = 123") to send data to PHP ");
PHP sends data to js, using echo json_encode ($ res); (Note that the construction of the variable $ res should comply with JSON specifications)
Js parses JSON data sent by PHP, using var obj = eval ('+ xmlHttp. responseText + ')');