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
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 returnfalse;
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】:
亮点在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
   
 
   