欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript用JSONP跨域請(qǐng)求數(shù)據(jù)實(shí)例詳解

 更新時(shí)間:2017年01月06日 11:16:20   作者:Huoty''s Blog  
Javascript跨域訪問(wèn)是web開(kāi)發(fā)者經(jīng)常遇到的問(wèn)題,什么是跨域,就是一個(gè)域上加載的腳本獲取或操作另一個(gè)域上的文檔屬性。下面這篇文章主要介紹了JavaScript用JSONP跨域請(qǐng)求數(shù)據(jù)的方法,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。

前言

最近因?yàn)楣ぷ餍枰枰褠?ài)詞霸的每日一句引入到頁(yè)面上,愛(ài)詞霸向外開(kāi)放了 API, 接口返回 json 數(shù)據(jù),為了讓頁(yè)面更輕巧,我沒(méi)有用 jQuery,而是直接純 js 寫(xiě)了一段代碼:

<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>

運(yùn)行之后數(shù)據(jù)并沒(méi)有獲取到,而是出現(xiàn)了如下錯(cuò)誤提示:

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.

這就是跨域請(qǐng)求的問(wèn)題。那么什么是跨域請(qǐng)求呢?瀏覽器出于安全方面的考慮,采用同源策略(Same origin Policy),即只允許與同域下的接口交互。

同域是指:

  1. 同協(xié)議:如都是 http 或者 https
  2. 同域名:如都是 http://konghy.cn/a 或 http://konghy.cn/b
  3. 同端口:如都是 80 端口

也就是說(shuō),用戶打開(kāi)了頁(yè)面: http://blog.konghy.cn, 當(dāng)前頁(yè)面下的 js 向 http://blog.konghy.cn/XXX 的接口發(fā)數(shù)據(jù)請(qǐng)求,瀏覽器是允許的。但假如向: http://open.iciba.com/xxx 發(fā)數(shù)據(jù)請(qǐng)求則會(huì)被瀏覽器阻止掉,因?yàn)榇嬖诳缬蛘{(diào)用。

跨域請(qǐng)求的解決辦法就是 JSONP(JSON with Padding) . HTML 中 script 標(biāo)簽可以加載其他域下的 js, JSONP 就是通過(guò) script 標(biāo)簽加載數(shù)據(jù)的方式去獲取數(shù)據(jù)當(dāng)做 JS 代碼來(lái)執(zhí)行,然后再用一個(gè)回調(diào)函數(shù)抽取數(shù)據(jù):

<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>

再查查資料,發(fā)現(xiàn)有人做了封裝:

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 請(qǐng)求數(shù)據(jù):

<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>

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流。

參考資料

http://www.dbjr.com.cn/article/75669.htm

https://zhuanlan.zhihu.com/p/22600501

相關(guān)文章

最新評(píng)論