AJAX跨域請(qǐng)求獲取JSON數(shù)據(jù)

2022-05-17 14:35 更新
Asynchronous JavaScript and XML (AJAX ) 是驅(qū)動(dòng)新一代 Web 站點(diǎn)(流行術(shù)語(yǔ)為 Web 2.0 站點(diǎn))的關(guān)鍵技術(shù)。Ajax 允許在不干擾 Web 應(yīng)用程序的顯示和行為的情況下在后臺(tái)進(jìn)行數(shù)據(jù)檢索。使用 XMLHttpRequest 函數(shù)獲取數(shù)據(jù),它是一種 API,允許客戶端 JavaScript 通過 HTTP 連接到遠(yuǎn)程服務(wù)器。Ajax 也是許多 mashup 的驅(qū)動(dòng)力,它可將來自多個(gè)地方的內(nèi)容集成為單一 Web 應(yīng)用程序。

我們都知道,由于受到瀏覽器的限制,AJAX 是不允許跨域請(qǐng)求。不過可以通過使用 JSONP 來實(shí)現(xiàn)。JSONP 是一種通過腳本標(biāo)記注入的方式,它是可以引用跨域 URL 的 js 腳本,不過需要提供一個(gè)回調(diào)函數(shù)(必須在您自己的頁(yè)面上),因此,你可以自己處理結(jié)果。 本文介紹了 JSONP 的是怎么在 jQuery,MooTools 的,Dojo Toolkit 中實(shí)現(xiàn)的。 

jQuery 的 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) 是一個(gè)非官方的協(xié)議,它允許在服務(wù)器端集成 Script tags 返回至客戶端,通過 javascript callback 的形式實(shí)現(xiàn)跨域訪問(這僅僅是 JSONP 簡(jiǎn)單的實(shí)現(xiàn)形式)。

2. JSONP有什么用

由于同源策略的限制,XmlHttpRequest 只允許請(qǐng)求當(dāng)前源(域名、協(xié)議、端口)的資源,為了實(shí)現(xiàn)跨域請(qǐng)求,可以通過 script 標(biāo)簽實(shí)現(xiàn)跨域請(qǐng)求,然后在服務(wù)端輸出 JSON 數(shù)據(jù)并執(zhí)行回調(diào)函數(shù),從而解決了跨域的數(shù)據(jù)請(qǐng)求。


jQuery.getJSON 方法:


Js 代碼如下:

jQuery.getJSON("http://search.twitter.com/search.json?callback=?",{ 
    q: "Arsenal" 
},function(tweets) { 
    // Handle response here 
    console.info("Twitter returned: ",tweets); 
});

或者類似


Js 代碼如下:

$.ajax({ 
         type:"get", 
         data:"random = "+Math.random(), 
         url:url, 
         dataType:"jsonp", 
         jsonp:"callback", 
         success:function(data){ 
         $.each(data, function(key, val) { 
         $("#myDiv").html($("#myDiv").html()+val.cvalue+"</br>"); 
         }); 
        } 
      }); 

回調(diào)方法的參數(shù)通過 getJSON 就可以獲取到 json 對(duì)象

MooTools JSONP

MooTools 需要 Request.JSONP Class,可以從這里下載 MooTools More。選擇 Request.JSONP

這樣從另一個(gè)域獲取 JSON 就是小菜一碟了


Js 代碼如下:

new Request.JSONP({ 
    url: "http://search.twitter.com/search.json", 
    data: { 
        q: "Arsenal" 
    },//提交的參數(shù), 沒有參數(shù)可以不寫 
        callbackKey: 'jsoncallback',//自己定義回調(diào)函數(shù)的參數(shù)名稱 
        onComplete: function(tweets) { 
        // Log the result to console for inspection 
        console.info("Twitter returned: ",tweets); 
    } 
}).send(); 

如果自己定義了回調(diào)函數(shù)的參數(shù)名稱,跟 jquery 一樣


服務(wù)器端你需要這樣去取得:


Js 代碼如下:

String callback = request.getParameter("jsoncallback");//取得回調(diào)方法名 
        response.setHeader("Cache-Control", "no-cache"); 
        response.setContentType("text/json;charset = UTF-8"); 
        PrintWriter out; 
        try { 
            out = response.getWriter(); 
            out.print(callback+"("+message+")");//這里是關(guān)鍵.主要就是這里 
            out.flush(); 
            out.close(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 

順便說一句:個(gè)人比較喜歡 mootools 的語(yǔ)法結(jié)構(gòu),和框架設(shè)計(jì)思路,再次贊美!


Dojo JSONP

JSONP 在 Dojo Toolkit 中需要用上 dojo.io.script (點(diǎn)擊可以查看示例)


Js 代碼如下:

// dojo.io.script is an external dependency, so it must be required 
dojo.require("dojo.io.script"); 

// When the resource is ready 
dojo.ready(function() { 

    // Use the get method 
    dojo.io.script.get({ 
        // The URL to get JSON from Twitter 
        url: "http://search.twitter.com/search.json", 
        // The callback paramater 
        callbackParamName: "callback", // Twitter requires "callback" 
        // The content to send 
        content: { 
            q: "Arsenal" 
        }, 
        // The success callback 
        load: function(tweetsJson) {  // Twitter sent us information! 
            // Log the result to console for inspection 
            console.info("Twitter returned: ",tweetsJson); 
        } 
    }); 
}); 

JSONP 是一種非常有效的,可靠的,容易實(shí)現(xiàn)的遠(yuǎn)程數(shù)據(jù)獲取方式。JSONP 的策略也使開發(fā)人員能夠避免繁瑣的服務(wù)器代理方式,很方便的獲取數(shù)據(jù)。

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

客戶端代碼:

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />  
  <script type="text/javascript">  
    function jsonpCallback(result) {  
      //alert(result);  
      for(var i in result) {  
        alert(i+":"+result[i]);  //循環(huán)輸出a:1, b:2, etc.  
      }  
    }  
    var JSONP=document.createElement("script");  
    JSONP.type = "text/javascript";  
    JSONP.src = "http://crossdomain.com/services.php?callback = jsonpCallback";  
    document.getElementsByTagName("head")[0].appendChild(JSONP);  
  </script>

服務(wù)端代碼:

<?php  
  
    //服務(wù)端返回 JSON 數(shù)據(jù)  
    $arr=array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);  
    $result=json_encode($arr);  
    //echo $_GET['callback'].'("Hello,World!")';  
    //echo $_GET['callback']."($result)";  
    //動(dòng)態(tài)執(zhí)行回調(diào)函數(shù)  
    $callback = $_GET['callback'];  
    echo $callback."($result)";

相關(guān)教程

AJAX教程


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)