標籤:javascript與php使用json
javascript:<script>/*@desc 載入XHR檔案@author lee [<[email protected]>]@param file 檔案路徑@param async 同步或非同步 true 非同步 flase 同步@return xmlDoc 載入後的內容*/function loadDoc(file,async=true){if(window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest();}else{ // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}if(async === true){ xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState < 4){ // 載入中 }else if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ // 成功 var xmlDoc if(xmlhttp.getResponseHeader(‘content-type‘)===‘application/json‘){ xmlDoc = JSON.parse(xmlhttp.responseText); }else{ xmlDoc = xmlhttp.responseText } return xmlDoc }else{ // 失敗 xmlhttp.abort() return } }}xmlhttp.open("POST",file,async);xmlhttp.setRequestHeader("Content-type", "application/json");var data = {name:"lee"}var str = JSON.stringify(data)xmlhttp.send(str);if(async === false){ var xmlDoc if(xmlhttp.getResponseHeader(‘content-type‘)===‘application/json‘){ xmlDoc = JSON.parse(xmlhttp.responseText); }else{ xmlDoc = xmlhttp.responseText } return xmlDoc}}var str = loadDoc(‘test.php‘,false)console.log(str.name)</script>
php:<?phpheader("content-type:application/json");$json = file_get_contents(‘php://input‘);echo $json;
javascript與php使用json進行資料通訊