1.本地jsonp.htmljavascript
<!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript" src="http://localhost/Vitaproject/jsonp.js"></script> </head> <body> </body> </html>
遠程jsonp.jshtml
alert("ok")
2.本地jsonp.htmljava
<!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript"> //回調函數 function callback(data) { alert(data.message); } </script> <script type="text/javascript" src="http://localhost/Vitaproject/jsonp.js"></script> </head> <body> </body> </html>
遠程jsonp.jsjquery
//調用callback函數,並以json數據形式做爲闡述傳遞,完成回調 callback({message:"success"});
3.JSajax
本地jsonp.htmljson
<!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript"> // 獲得航班信息查詢結果後的回調函數 var flightHandler = function(data){ alert('你查詢的航班結果是:票價 ' + data.price + ' 元,' + '餘票 ' + data.tickets + ' 張。'); }; // 提供jsonp服務的url地址(不論是什麼類型的地址,最終生成的返回值都是一段javascript代碼) var url = "http://localhost/Vitaproject/flightResult.asp?code=CA1998&callback=flightHandler"; // 建立script標籤,設置其屬性 var script = document.createElement('script'); script.setAttribute('src', url); // 把script標籤加入head,此時調用開始 document.getElementsByTagName('head')[0].appendChild(script); </script> </head> <body> </body> </html>
http://localhost/Vitaproject/flightResult.aspapp
flightHandler({ "code": "CA1998", "price": 1780, "tickets": 5 });
4.jQjeryasync
本地jsonp.html函數
<!DOCTYPE html> <html> <head> <title>Untitled Page</title> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ $.ajax({ type: "get", async: false, url: "http://localhost/Vitaproject/flightResult.asp?code=CA1998", dataType: "jsonp", jsonp: "callback",//傳遞給請求處理程序或頁面的,用以得到jsonp回調函數名的參數名(通常默認爲:callback) jsonpCallback:"flightHandler",//自定義的jsonp回調函數名稱,默認爲jQuery自動生成的隨機函數名,也能夠寫"?",jQuery會自動爲你處理數據 success: function(json){ alert('您查詢到航班信息:票價: ' + json.price + ' 元,餘票: ' + json.tickets + ' 張。'); }, error: function(){ alert('fail'); } }); }); </script> </head> <body> </body> </html>
http://localhost/Vitaproject/flightResult.aspjsonp
flightHandler({ "code": "CA1998", "price": 1780, "tickets": 5 });
4.
<!DOCTYPE html> <html> <head> <title>Untitled Page</title> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ $.ajax({ type: "get", url:"http://m.qqdyw.cn/lottery/draw/key/", //url:"http://www.jibuu.cn/Main/AjaxServer.aspx?Action=GetActListForDefault", dataType:'jsonp', jsonp:'callback', success:function(result) { console.log(result); alert(result.status) }, error: function(){ alert('fail'); } }); }); </script> </head> <body> </body> </html>
({"status":0,"award":"\u4eb2\uff0c\u4e0d\u54ed","item":0})