1. 程式人生 > >javascript與php使用json進行數據通信

javascript與php使用json進行數據通信

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:
    <?php
    header("content-type:application/json");
    $json = file_get_contents(‘php://input‘);
    echo $json;
  • javascript與php使用json進行數據通信