標籤: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})