php接收post過來的 json資料 例子

來源:互聯網
上載者:User

標籤:script   localhost   alert   origin   注意   代碼   方式   click   3.2   

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的資訊

 

php接收post過來的 json資料 例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.