Communication between PHP and js (via ajax, json)

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.