ajax+jsonp

Ajax

Asynchronous JavaScript and XML (Ajax ) 是驅動新一代 Web 站點(流行術語爲 Web 2.0 站點)的關鍵技術。Ajax 允許在不干擾 Web 應用程序的顯示和行爲的情況下在後臺進行數據檢索。使用 XMLHttpRequest 函數獲取數據,它是一種 API,允許客戶端 JavaScript 通過 HTTP 連接到遠程服務器。Ajax 也是許多 mashup 的驅動力,它可將來自多個地方的內容集成爲單一 Web 應用程序。

同域請求

直接上代碼

index.html

<html>
<head>
    <script type="text/javascript">
        function loadXMLDoc(){
            var xmlhttp;
            if (window.XMLHttpRequest){
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }else{
                // code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.onreadystatechange=function(){
                if (xmlhttp.readyState==4 && xmlhttp.status==200){
                    jsondata = xmlhttp.responseText;
                    var jsonobj = JSON.parse(jsondata);
                    document.getElementById("myDiv").innerHTML="<h3>" + jsonobj.name + "</h3>";
                }
            }
            //GET請求方式
            // xmlhttp.open("GET", "/test/demo/json/index.php?content=123", true);
            // xmlhttp.send();
            //POST請求方式
            xmlhttp.open("POST", "http://www.a.com/test/demo/json/json.php", true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send("name=jack");
        }
    </script>
</head>
<body>

    <div id="myDiv"><h3>Let AJAX change this text</h3></div>
    <button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

json.php

<?php
    /**
     * 
     * @authors Yiwei Xia ([email protected])
     * @date    2015-06-21
     * @version Version1.0
     */
    //下面兩個header允許其他域訪問,不過IE>=10,chrome,firefox支持
    //header("Access-Control-Allow-Origin:*");
    //header("Access-Control-Allow-Methods:POST,GET");
    if (isset($_GET["content"])) {
        $content = $_GET["content"];
        echo "get it $content";
        return;
    }elseif(isset($_POST["name"])){
        $name = $_POST["name"];
        $arr = array('name' => $name, );
        echo json_encode($arr);
        return;
    }

?>

跨域請求

第一種方式

CROS

在服務端加入下面兩個代碼,不過僅IE>=10,chrome,firefox支持,代碼見上面兩段

header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:POST,GET");

第二種方式

採用jsonp

1、什麼是JSONP?

要了解JSONP,不得不提一下JSON,那麼什麼是JSON ?

JSON is a subset of the object literal notation of JavaScript. Since JSON is 

a subset of JavaScript, it can be used in the language with no muss or fuss.

JSONP(JSON with Padding)是一個非官方的協議,它允許在服務器端集成Script tags返回至客戶端,通過javascript callback的形式實現跨域訪問(這僅僅是JSONP簡單的實現形式)。

2、JSONP有什麼用?

由於同源策略的限制,XmlHttpRequest只允許請求當前源(域名、協議、端口)的資源,爲了實現跨域請求,可以通過script標籤實現跨域請求,然後在服務端輸出JSON數據並執行回調函數,從而解決了跨域的數據請求。

3、如何使用JSONP?

下邊這一DEMO實際上是JSONP的簡單表現形式,在客戶端聲明回調函數之後,客戶端通過script標籤向服務器跨域請求數據,然後服務端返回相應的數據並動態執行回調函數。

代碼如下

index.html

<html>
<head>
    <script type="text/javascript">
        //回調函數
        function userinfo(result){
            document.getElementById("myDiv").innerHTML="<h3>" + result.username + "</h3>";
        }
        function get_userinfo(){
            var eleScript= document.createElement("script");
            eleScript.type = "text/javascript";
            eleScript.src = "http://www.a.com/test/demo/json/jsonp.php?callback=userinfo";
            document.getElementsByTagName("HEAD")[0].appendChild(eleScript);
        }
    </script>

</head>
<body>

    <div id="myDiv"><h3>Let AJAX change this text</h3></div>
    <button type="button" onclick="get_userinfo()">Change Content</button>

</body>
</html>

jsonp.php

<?php
    /**
     * 
     * @authors Yiwei Xia ([email protected])
     * @date    2015-06-21
     * @version Version1.0
     */
    if (isset($_GET["callback"])) {
        $callback = $_GET["callback"];
        if ($callback == "userinfo") {
            $userinfo = '{"username":"jack","password":"jack"}';
            //回調函數
            echo $callback."($userinfo)";
        }
    }

?>

jQuery實現JSONP

沒法按照callback返回

index2.html

<!-- jQuery -->
<html>
<head>
    <script type="text/javascript" src="jquery-1.11.3.min.js"></script>  
    <script type="text/javascript">
        function get_userinfo(){
            //jQuery方法1
            $.getJSON("http://www.a.com/test/demo/json/jsonp.php?callback=?",
            function(result) {
                document.getElementById("myDiv").innerHTML="<h3>" + result.username + "</h3>";
            });
            //  jQuery方法2
            // $.ajax({
            //     url:"http://www.a.com/test/demo/json/jsonp.php",
            //     dataType:'jsonp',
            //     data:'',
            //     jsonp:'callback',
            //     success:function(result) {
            //         document.getElementById("myDiv").innerHTML="<h3>" + result.username + "</h3>";
            //     },
            //     timeout:3000
            // });
            //jQuery方法3
            // $.get('http://www.a.com/test/demo/json/jsonp.php?callback=?', {name: encodeURIComponent('test')}, function (result) {document.getElementById("myDiv").innerHTML="<h3>" + result.username + "</h3>";}, 'jsonp');
        }
    </script>

</head>
<body>

    <div id="myDiv"><h3>Let AJAX change this text</h3></div>
    <button type="button" onclick="get_userinfo()">Change Content</button>

</body>
</html>

服務端

<?php
/**
 * 
 * @authors Yiwei Xia ([email protected])
 * @date    2015-06-21
 * @version Version1.0
 */
if (isset($_GET["callback"])) {
    $callback = $_GET["callback"];
    $userinfo = '{"username":"jack","password":"jack"}';
    //回調函數
    echo $callback."($userinfo)";
}

?>

Jsonp原理:

首先在客戶端註冊一個callback, 然後把callback的名字傳給服務器。

此時,服務器先生成 json 數據。

然後以 javascript 語法的方式,生成一個function , function 名字就是傳遞上來的參數 jsonp.

最後將 json 數據直接以入參的方式,放置到 function 中,這樣就生成了一段 js 語法的文檔,返回給客戶端。

客戶端瀏覽器,解析script標籤,並執行返回的 javascript 文檔,此時數據作爲參數,傳入到了客戶端預先定義好的 callback 函數裏.(動態執行回調函數)

使用JSON的優點在於:

  • 比XML輕了很多,沒有那麼多冗餘的東西。

  • JSON也是具有很好的可讀性的,但是通常返回的都是壓縮過後的。不像XML這樣的瀏覽器可以直接顯示,瀏覽器對於JSON的格式化的顯示就需要藉助一些插件了。

  • 在JavaScript中處理JSON很簡單。

  • 其他語言例如PHP對於JSON的支持也不錯。

JSON也有一些劣勢:

  • JSON在服務端語言的支持不像XML那麼廣泛,不過JSON.org上提供很多語言的庫。

  • 如果你使用eval()來解析的話,會容易出現安全問題。

儘管如此,JSON的優點還是很明顯的。他是Ajax數據交互的很理想的數據格式。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章