PHP and JS communication (via Ajax,json) _javascript tips

Source: Internet
Author: User
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 + ') ');

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.