AJAX跨域請求json資料的實現方法_javascript技巧

來源:互聯網
上載者:User
我們都知道,AJAX的一大限制是不允許跨域請求。 不過通過使用JSONP來實現。JSONP是一種通過指令碼標記注入的方式,它是可以引用跨域URL的js指令碼,不過需要提供一個回呼函數(必須在您自己的頁面上),因此,你可以自己處理結果。 讓我們看看JSONP的是怎麼在jQuery,MooTools的,Dojo Toolkit中實現的。

jQuery的JSONP
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>");
                      });
                }
            });

回調方法的參數 通過getJSON 就可以擷取 到json對象

MooTools JSONP
MooTools 需要Request.JSONP Class , 可以從這裡下載MooTools More .  選擇Request.JSONP,
這樣 從另一個域擷取json就是小菜一碟了.

Js代碼
複製代碼 代碼如下:

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

如果自己定義了回呼函數的參數名稱. 跟jquery一樣.

伺服器端你需要這樣去取得:

Js代碼
複製代碼 代碼如下:

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

順便說一句: 個人比較喜歡mootools的文法結構,和架構設計思路. 再次讚美!

Dojo JSONP
JSONP 在Dojo Toolkit 中需要用上dojo.io.script (點擊可以查看樣本)

 
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是一種非常有效,可靠的,容易實現的遠端資料擷取方式。JSONP的策略也使開發人員能夠避免繁瑣的伺服器代理方式,很方便的擷取資料。 你可以自己寫一個試試
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.