javascript与php使用json进行数据通信
更新:HHH   时间:2023-1-7


  1. javascript:
    <script>
    /*
    @desc 加载XHR文件
    @author lee [<complet@163.com>]
    @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>
  2. php:
    <?php
    header("content-type:application/json");
    $json = file_get_contents('php://input');
    echo $json;
返回web开发教程...