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!
Code
1 < Script Type = "Text/JavaScript" >
2 Function Getjson (){
3 VaR XMLHTTP;
4 Try {
5 // Firefox, opera 8.0 +, Safari
6 XMLHTTP = New XMLHttpRequest ();
7 }
8 Catch (E ){
9 // Internet Explorer
10 Try {
11 XMLHTTP = New Activexobject ( " Msxml2.xmlhttp " );
12 }
13 Catch (E ){
14
15 Try {
16 XMLHTTP = New Activexobject ( " Microsoft. XMLHTTP " );
17 }
18 Catch (E ){
19 Alert ( " Your browser does not support Ajax! " );
20 Return False ;
21 }
22 }
23 }
24
25 XMLHTTP. onreadystatechange = Function (){
26 If (XMLHTTP. readystate = 4 ){
27 // Alert (XMLHTTP. responsetext );
28 VaR Str = XMLHTTP. responsetext;
29 Document. getelementbyid ( ' Show ' ). Innerhtml + = STR;
30 // Alert (STR );
31 VaR OBJ = Eval ( ' ( ' + XMLHTTP. responsetext + ' ) ' );
32 // VaR OBJ = eval ({"ID": "123", "name": "elar", "Age": "21 "}));
33 Alert (obj. Name );
34 }
35 }
36 VaR Data = " Id = 123 " ;
37 XMLHTTP. Open ( " Post " , " Testjson. php " , True );
38 XMLHTTP. setRequestHeader ( " Content-Type " , " Application/X-WWW-form-urlencoded " );
39 XMLHTTP. Send ( " Id = 123 " );
40 }
41 </ Script >
42 < Input Type = "Button" Onclick = "Getjson ()" Value = "Press me! " />
43 < HR />
44 < 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
1 <? PHP
2 $ Res [ ' ID ' ] = $ _ Post [ ' ID ' ];
3 $ Res [ ' Name ' ] = " Elar " ;
4 $ Res [ ' Age ' ] = " 21 " ;
5 $ Response = " Hello this is response " . $ _ Post [ ' ID ' ];
6 Echo Json_encode ( $ Res );
7 ?>
Summary:
JS needs to send data to the PHP end, which isXMLHTTP. Send ("Id = 123");
PHP sends data to JS and usesEchoJson_encode ($ Res); (Note that the structure of the variable $ res should comply with the JSON specification)
JS parses JSON-format data sent by PHP.VaROBJ=Eval ('('+XMLHTTP. responsetext+')');
---------- About JSON vs eval -- Google