AJAX跨域請求獲取JSON數(shù)據(jù)的實現(xiàn)方法
Asynchronous JavaScript and XML (AJAX ) 是驅(qū)動新一代 Web 站點(流行術(shù)語為 Web 2.0 站點)的關(guān)鍵技術(shù)。Ajax 允許在不干擾 Web 應(yīng)用程序的顯示和行為的情況下在后臺進(jìn)行數(shù)據(jù)檢索。使用 XMLHttpRequest 函數(shù)獲取數(shù)據(jù),它是一種 API,允許客戶端 JavaScript 通過 HTTP 連接到遠(yuǎn)程服務(wù)器。Ajax 也是許多 mashup 的驅(qū)動力,它可將來自多個地方的內(nèi)容集成為單一 Web 應(yīng)用程序。
我們都知道,由于受到瀏覽器的限制,AJAX 是不允許跨域請求。不過可以通過使用 JSONP 來實現(xiàn)。JSONP 是一種通過腳本標(biāo)記注入的方式,它是可以引用跨域 URL 的 js 腳本,不過需要提供一個回調(diào)函數(shù)(必須在您自己的頁面上),因此,你可以自己處理結(jié)果。 本文介紹了 JSONP 的是怎么在 jQuery,MooTools 的,Dojo Toolkit 中實現(xiàn)的。
jQuery 的 JSONP1. 什么是 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) 是一個非官方的協(xié)議,它允許在服務(wù)器端集成 Script tags 返回至客戶端,通過 javascript callback 的形式實現(xiàn)跨域訪問(這僅僅是 JSONP 簡單的實現(xiàn)形式)。
2. JSONP有什么用由于同源策略的限制,XmlHttpRequest 只允許請求當(dāng)前源(域名、協(xié)議、端口)的資源,為了實現(xiàn)跨域請求,可以通過 script 標(biāo)簽實現(xiàn)跨域請求,然后在服務(wù)端輸出 JSON 數(shù)據(jù)并執(zhí)行回調(diào)函數(shù),從而解決了跨域的數(shù)據(jù)請求。
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 對象
MooTools JSONPMooTools 需要 Request.JSONP Class,可以從這里下載 MooTools More。選擇 Request.JSONP
這樣從另一個域獲取 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(); }順便說一句:個人比較喜歡 mootools 的語法結(jié)構(gòu),和框架設(shè)計思路,再次贊美!
Dojo JSONPJSONP 在 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 是一種非常有效的,可靠的,容易實現(xiàn)的遠(yuǎn)程數(shù)據(jù)獲取方式。JSONP 的策略也使開發(fā)人員能夠避免繁瑣的服務(wù)器代理方式,很方便的獲取數(shù)據(jù)。
JSONP (JSON with Padding) 是一個非官方的協(xié)議,它允許在服務(wù)器端集成 Script tags 返回至客戶端,通過 javascript callback 的形式實現(xiàn)跨域訪問(這僅僅是 JSONP 簡單的實現(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)'; //動態(tài)執(zhí)行回調(diào)函數(shù) $callback = $_GET['callback']; echo $callback.'($result)';到此這篇關(guān)于AJAX跨域請求獲取JSON數(shù)據(jù)的文章就介紹到這了,更多相關(guān)AJAX跨域請求獲取JSON數(shù)據(jù)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
