【入门】PHP 与 js的通信(via ajax,json)

JavaScript端:

注意:一定要设置xmlHttp.setRequestHeader,否则传往PHP的参数会变成null(line 38)

亮点在line 31!

代码
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("您的浏览器不支持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="按我!"/>
43 <hr />
44 <div id="show"></div>

PHP端【testJson.php】:

(注意,php文件要干净,<?php ?>标签的外部不能有其他标签,否则eval函数无法解析)

亮点在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 ?>

总结:

js要往PHP端送数据,用的是xmlHttp.send("id=123");

PHP给js送数据,用的是echo json_encode($res);(要注意变量$res的构造应符合JSON的规范)

js要解析PHP送来的JSON格式的数据,用var obj = eval('('+ xmlHttp.responseText +')');


----------关于 json VS eval 请 --Google

原文地址:https://www.cnblogs.com/elaron/p/1878369.html