來個例子:(json.html)javascript
<html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="js/jquery.js"></script> </head> <body> <input type="button" value="submit" id="submit"> <div id="txt">&</div> <script> //監聽對象 document.getElementById('submit').onclick = function(){ post("json.php","name=復讀機1&age=123",function(data){ console.log(data); },"json") } //簡單的post封裝 function post(url,data,callback,dataType){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ callback(JSON.parse(xhr.responseText)); } } xhr.open("post",url,true); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded") xhr.send(data); } </script> </body> </html>
json.phpphp
<?php $info = array("name"=>"復讀機2","age"=>223); $infoencode = json_encode($info);//轉化爲json格式 echo $infoencode; ?>
若是php文件是gb2312格式,把變量值轉化爲utf-8格式的,由於json_encode函數的參數必須是utf-8:html
<?php $info = array("name"=>"復讀機2","age"=>223); foreach($info as $name => $value){ $infogb["$name"] = iconv('gb2312','utf-8',$value); } $infoencode = json_encode($infogb); echo $infoencode; ?>
總結一下:前端向後端請求發送的數據仍是查詢字符串格式,然後端向前端響應的數據爲json格式以便於用javascript解析。前端