前言
最近因為工作需要,需要把愛詞霸的每日一句引入到頁面上,愛詞霸向外開放了 API, 接口返回 json 數據,為了讓頁面更輕巧,我沒有用 jQuery,而是直接純 js 寫了一段代碼:
<script type="text/javascript"> function httpGetAsync(theUrl, callback) { xmlHttp = null; if (window.XMLHttpRequest) {// code for IE7, Firefox, Opera, etc. xmlHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) {// code for IE6, IE5 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlHttp != null) { xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { callback(xmlHttp.responseText); } else { console.error("Problem retrieving XML data"); } } xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*'); xmlHttp.send(null); } else { console.error("Your browser does not support XMLHTTP."); } } function showIcibaDS(ds_data) { // show daily sentence content = ds_data.content; note = ds_data.note; document.write(content + '<br>'); document.write(note); } httpGetAsync("http://open.iciba.com/dsapi/", showIcibaDS);</script>
運行之后數據并沒有獲取到,而是出現了如下錯誤提示:
XMLHttpRequest cannot load http://open.iciba.com/dsapi/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 501.
這就是跨域請求的問題。那么什么是跨域請求呢?瀏覽器出于安全方面的考慮,采用同源策略(Same origin Policy),即只允許與同域下的接口交互。
同域是指:
也就是說,用戶打開了頁面: http://blog.konghy.cn, 當前頁面下的 js 向 http://blog.konghy.cn/XXX 的接口發數據請求,瀏覽器是允許的。但假如向: http://open.iciba.com/xxx 發數據請求則會被瀏覽器阻止掉,因為存在跨域調用。
跨域請求的解決辦法就是 JSONP(JSON with Padding) . HTML 中 script 標簽可以加載其他域下的 js, JSONP 就是通過 script 標簽加載數據的方式去獲取數據當做 JS 代碼來執行,然后再用一個回調函數抽取數據:
<script type="text/javascript"> var cur_date = new Date(); document.getElementById("cur_year").innerHTML = cur_date.getFullYear(); function showIcibaDS(ds_data) { // show daily sentence content = ds_data.content; note = ds_data.note; ds_p = document.getElementById("iciba_ds") var content_span = document.createElement('span'); var note_span = document.createElement('span'); var br = document.createElement('br') content_span.innerHTML = content note_span.innerHTML = note ds_p.appendChild(content_span); ds_p.appendChild(br); ds_p.appendChild(note_span); }</script><script type="text/javascript" src="http://open.iciba.com/dsapi/?callback=showIcibaDS"></script>
再查查資料,發現有人做了封裝:
function jsonp(setting){ setting.data = setting.data || {} setting.key = setting.key||'callback' setting.callback = setting.callback||function(){} setting.data[setting.key] = '__onGetData__' window.__onGetData__ = function(data) { setting.callback (data); } var script = document.createElement('script') var query = [] for(var key in setting.data) { query.push(key + '=' + encodeURIComponent(setting.data[key])) } script.src = setting.url + '?' + query.join('&') document.head.appendChild(script) document.head.removeChild(script)}jsonp({ url: 'http://photo.sina.cn/aj/index', key: 'jsoncallback', data: { page: 1, cate: 'recommend' }, callback: function(ret) { console.log(ret) }})
如果你使用的是 jQuery,則可以直接用 ajax 請求數據:
<script src="js/jquery-1.11.3.js"></script><script>$(function(){ $.ajax({ async: true, type: "GET", dataType: 'jsonp', jsonp: 'callback', jsonpCallback: 'callbackfunction', url: "http://open.iciba.com/dsapi/", data: "", timeout: 3000, contentType: "application/json;utf-8", success: function(data) { console.log(data); } });})</script>
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
參考資料
//www.companysz.com/article/75669.htm
https://zhuanlan.zhihu.com/p/22600501
|
新聞熱點
疑難解答