码迷,mamicode.com
首页 > 编程语言 > 详细

javascript与php使用json进行数据通信

时间:2018-03-25 12:08:00      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:javascript与php使用json

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

    标签:javascript与php使用json

    原文地址:http://blog.51cto.com/12173069/2090803

    (0)
    (0)
       
    举报
    评论 一句话评论(0
    登录后才能评论!
    © 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
    迷上了代码!