JSONP使用筆記

來源:互聯網
上載者:User

標籤:style   blog   http   java   color   get   

 JSONP

  JSONP是實現跨域GET請求的一種方法, 原理上利用script標籤可以動態載入JS檔案,

將不同來源站點點的JSON資料載入到本網站來,如果給定回呼函數,將回呼函數名傳遞到伺服器端,

在伺服器端產生 此函數以JSON資料為入參的調用語句,就為一般AJAX實現的getJSON介面。

getJSON介面如果請求URL與當前URL一致,則為一般網站訪問。

 

下文給出詳盡的解釋

http://www.cnblogs.com/yuzhongwusan/archive/2012/12/11/2812849.html

 

實驗

jsonpServer.php

<?php$jsondata = "{symbol:‘IBM‘, price:120}";  echo $_GET[‘callback‘].‘(‘.$jsondata.‘)‘; ?>

 

 

jsonpClient.html

<html><head>         <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>        <style>        </style></head> <body>        <h1>hello world!</h1>         <input type="text" value="test"/>         <input type="button" value="button"/>         <script type=‘text/javascript‘>             $("[type=‘button‘]").click(function(){                //JQuery JSONP Support                  var url = "http://127.0.0.1/jsonpServer.php?callback=?";                  $.getJSON(url, function(data){                      var retMsg = "Symbol:" + data.symbol + ", Price:" + data.price;                      $("[type=‘text‘]").val(retMsg);                });             })        </script></body></html>

 

 

用戶端使用者訪問 http://localhost/jsonpClient.html,  

點擊按鈕,發起JSONP請求,

GET http://127.0.0.1/jsonpServer.php?callback=jQuery18305268568145111203_1403193771906&_=1403194058203 HTTP/1.1
Host: 127.0.0.1
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
Referer: http://localhost/jsonpClient.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8,en-GB;q=0.6,en;q=0.4

伺服器端響應內容為,可見$.getJSON檢測URL中有callback=?, 表示將第二個參數作為回呼函數,

但是第二個函數為 匿名函數, 所以就給此函數重新命名一個複雜長串, 以備響應時候觸發調用。 

HTTP/1.1 200 OK
Date: Thu, 19 Jun 2014 16:07:38 GMT
Server: Apache/2.4.7 (Win32) OpenSSL/0.9.8y PHP/5.4.25
X-Powered-By: PHP/5.4.25
Content-Length: 67
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

jQuery18305268568145111203_1403193771906({symbol:‘IBM‘, price:120})

 

 

 

 

 

 

聯繫我們

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