php接收post過來的 json數據 例子


html代碼

<html>
<head>
    <title>json</title>
    <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.js"></script>
</head>
<body>
    json
    <input type="button" onclick="sendJson()" value="點擊">
</body>

<script>
    function sendJson() {

        var stu={
            name:"冷榮富",
            age:22,
            sex:""
        };
        $.ajax({
            type : "POST",  //提交方式
            url : "http://localhost/jsonTest.php",//路徑,www根目錄下
            data : {
                "student" : stu
            },//數據,這里使用的是Json格式進行傳輸
            success : function(result) {//返回數據根據結果進行相應的處理
                alert(result);
            }
        });
    }
</script>
</html>

php代碼

<?php
    $student = $_POST['student'];
    echo $student['name'];
    echo $student['age'];
    echo $student['sex'];
?>

 這是在一台電腦上的,如果兩台電腦就設計到跨域的問題,html的代碼要把url改一下,php的代碼要加一個頭具體看代碼

html代碼

<html>
<head>
    <title>json</title>
    <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.js"></script>
</head>
<body>
    json
    <input type="button" onclick="sendJson()" value="點擊">
</body>

<script>
    function sendJson() {

        var stu={
            name:"冷榮富",
            age:22,
            sex:""
        };
        $.ajax({
            type : "POST",  //提交方式
            url : "http://211.83.247.14/TempServer/jsonTest.php",//注意!這個是跟上面不一樣的地方
            data : {
                "student" : stu
            },//數據,這里使用的是Json格式進行傳輸
            success : function(result) {//返回數據根據結果進行相應的處理
                alert(result);
            }
        });
    }
</script>
</html>

php代碼

<?php
    header('Access-Control-Allow-Origin:*');//注意!跨域要加這個頭 上面那個沒有
    $student = $_POST['student'];
    echo $student['name'];
    echo $student['age'];
    echo $student['sex'];
?>

這樣html那邊訪問后就會aler出echo的信息

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM