用 JSON 來實現 PHP 與 Javascript 間資料交換

JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式。

簡而論之,不管是xml還是json都是為了方便在客戶端與服務器端交互資料的中轉站,特別是用於物件型資料,比如最常見的數組。

下面將分別將數組從php傳送給javascript,以及將數組從javascript傳送給php示例說明,例子比較簡單,明白概念即可。不管從php傳送給javascript,還是javascript傳送給php,json在傳送之前都會將物件扁平化即一維化為字符串。
PHP 向 JavaScript 傳值

PHP 文件 json.php

<?php

    $arr = array(

        'name' => '希亞',

        'nick' => 'Gonn',

        'contact' => array(

            'email' => 'gonnsai@163.com',

            'website' => 'http://www.nowamagic.net',

        )

    );

    $json_string = json_encode($arr);

    echo "getProfile($json_string)";

    ?>

光執行這個文件,其結果如下:

    getProfile({"name":"\u5e0c\u4e9a","nick":"Gonn",

        "contact":{"email":"gonnsai@163.com","website":"http:\/\/www.nowamagic.net"}})

json.php 是通過 json_encode 函式將數組扁平化,然後發送,相反有個 json_decode 函式。

那麼在 JavaScript 如何呼叫呢?很簡單,定義一個變量獲取 PHP 傳來的 Json,該 Json 具備物件的特性,我們可以用 array.name 這種方式來獲取該 Json 的屬性。

    <script type="text/javascript">

    function getProfile(str) {

        var arr = str;

        document.getElementById('name').innerHTML = arr.name;

        document.getElementById('nick').innerHTML = arr.nick;

        document.getElementById('email').innerHTML = arr.contact.email;

        document.getElementById('website').innerHTML = arr.contact.website;

    }

    </script>

    <body>

    <div id="name"></div>

    <div id="nick"></div>

    <div id="email"></div>

    <div id="website"></div>

    </body>

    <script type="text/javascript" src="json.php"></script>

運行結果如下:

    希亞

    Gonn

    gonnsai@163.com

    http://www.nowamagic.net
JavaScript 向 PHP 傳值

json_encode.html

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>json:From javascript To php</title>

    <script src="json2.js" type="text/javascript"></script>

    <script type="text/javascript">

    function JSON_test(o)

    {

        var user = {

            name:document.getElementById('txt_name').value,

            email:document.getElementById('txt_email').value,

            password:document.getElementById('txt_password').value

        }

        var json_string = JSON.stringify(user);

        document.getElementById('txt_json').value=json_string;

        alert("點擊確定後將提交表單");

        o.submit();

    }

    </script>

    </head>

     

    <body>

     

        <form id="form1" name="form1" method="post" action="json_encode.php" onsubmit="JSON_test(this);return flase;">

            <label for="txt_name">姓名</label>

            <p><input type="text" name="txt_name" id="txt_name" /></p>

            <label for="txt_email">郵箱</label>

            <p><input type="text" name="txt_email" id="txt_email" /></p>

            <p><label for="txt_password">密碼</label></p>

            <p><input type="text" name="txt_password" id="txt_password" /></p>

            <p><input type="text" name="txt_json" id="txt_json" />

                <label for="button"></label>

                <input type="submit" name="button" id="button" value="JSON" />

            </p>

        </form>

     

    </body>

    </html>

這裡javascript扁平化需要一個插件:http://www.json.org/json2.js,通過JSON.stringify(str)將物件扁平化然後傳送給php。

註:另有一個http://www.json.org/json.js,對應的是toJSONString方法。

    var last=obj.toJSONString(); //針對json.js

    var last=JSON.stringify(obj); //針對json2.js
json_encode.php

    <?php

        header('Content-Type: text/html; charset=utf-8');

        $json_string = $_POST["txt_json"];

        //echo $json_string;

        if(ini_get("magic_quotes_gpc")=="1")

        {

            $json_string=stripslashes($json_string);

        }

        $user = json_decode($json_string);

     

        echo var_dump($user);

     

        echo '<br /><br /><br /><br />';

        echo $user->name.'<br />';

        echo $user->email.'<br />';

        echo $user->password.'<br />';

    ?>

這裡就需要用到json_decode()這個函式,然後呼叫其中資料用 $obj->屬性即可。

留言

這個網誌中的熱門文章

c語言-關於#define用法

CMD常用網管指令

PHP 與 JavaScript 之間傳值利用 json