php+ajax+json GET和POST两种方式
<html> <head> <script type="text/javascript" src="json.js"></script> <script> //创建AJAX XMLHttpRequest对象 var xmlHttp = false; try{ xmlHttp = new Activexobject("Msxml2.XMLHTTP"); }catch(e){ try{ xmlHttp = new Activexobject("Microsoft.XMLHTTP"); }catch(e2){ xmlHttp = false; } } if(!xmlHttp && typeof XMLHttpRequest != 'undefined'){ xmlHttp = new XMLHttpRequest(); } //GET方式 function callServer(){ var city = document.getElementById("city").value; var state = document.getElementById("state").value; if((city == null) || (city == "")) return; if((state == null) || (state == "")) return; //build the url var url = "getZipCode.php?city="+ escape(city) +"&state="+ escape(state) +""; //alert(url); //open a conection to the server xmlHttp.open("GET",url,true); //回调函数 xmlHttp.onreadystatechange = updatePage; //send the request xmlHttp.send(null); } //POST方式 function callServer2(){ var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin","email": "brett@newInstance.com" }, { "firstName": "Jason", "lastName":"Hunter","email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold","email": "elharo@macfaq.com" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] } var url = "getZipCode.php?timeStamp=" + new Date().getTime(); //alert(url); xmlHttp.open("POST",url,true); xmlHttp.onreadystatechange = updatePage; xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.send(people.toJSONString()); //document.write(people.toJSONString()); } //回调处理函数 function updatePage(){ if(xmlHttp.readyState == 4){ var response = xmlHttp.responseText; //alert(response); document.getElementById("zipcode").value = response; } } </script> </head> <body> <form> <p>City: <input type="text" name="city" id="city" size="25" onChange="callServer2();"></p> <p>State: <input type="text" name="state" id="state" size="25" onChange="callServer2();"></p> <p>Zip Code:<input type="text" name="zipcode" id="zipcode" size="5"></p> </form> </body> </html>
[注意] toJSONString方法需要json.js支持~!
getZipCode.php
<? $HTTP_RAW_POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input"); $value=json_decode($HTTP_RAW_POST_DATA); echo $value->programmers[0]->lastName; ?>
以上是php5.2默认支持json,否则可以在json.org网站上面下载JSON.phps
<? require_once('JSON.phps'); $json = new Services_JSON(); $HTTP_RAW_POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input"); $value = $json->decode($HTTP_RAW_POST_DATA); echo $value->programmers[0]->firstName ?>