JavaScript用JSONP跨域請求數(shù)據(jù)實例詳解
前言
最近因為工作需要,需要把愛詞霸的每日一句引入到頁面上,愛詞霸向外開放了 API, 接口返回 json 數(shù)據(jù),為了讓頁面更輕巧,我沒有用 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>
運行之后數(shù)據(jù)并沒有獲取到,而是出現(xiàn)了如下錯誤提示:
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),即只允許與同域下的接口交互。
同域是指:
- 同協(xié)議:如都是 http 或者 https
- 同域名:如都是 http://konghy.cn/a 或 http://konghy.cn/b
- 同端口:如都是 80 端口
也就是說,用戶打開了頁面: http://blog.konghy.cn, 當前頁面下的 js 向 http://blog.konghy.cn/XXX 的接口發(fā)數(shù)據(jù)請求,瀏覽器是允許的。但假如向: http://open.iciba.com/xxx 發(fā)數(shù)據(jù)請求則會被瀏覽器阻止掉,因為存在跨域調(diào)用。
跨域請求的解決辦法就是 JSONP(JSON with Padding) . HTML 中 script 標簽可以加載其他域下的 js, JSONP 就是通過 script 標簽加載數(shù)據(jù)的方式去獲取數(shù)據(jù)當做 JS 代碼來執(zhí)行,然后再用一個回調(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 請求數(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é)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
參考資料
http://www.dbjr.com.cn/article/75669.htm
https://zhuanlan.zhihu.com/p/22600501
相關文章
js+HTML5實現(xiàn)canvas多種顏色漸變效果的方法
這篇文章主要介紹了js+HTML5實現(xiàn)canvas多種顏色漸變效果的方法,涉及html5屬性的相關技巧,需要的朋友可以參考下2015-06-06
JavaScript數(shù)據(jù)操作_淺談原始值和引用值的操作本質(zhì)
下面小編就為大家?guī)硪黄狫avaScript數(shù)據(jù)操作_淺談原始值和引用值的操作本質(zhì)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08
layui的布局和表格的渲染以及動態(tài)生成表格的方法
今天小編就為大家分享一篇layui的布局和表格的渲染以及動態(tài)生成表格的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09
基于BootStrap Metronic開發(fā)框架經(jīng)驗小結(jié)【一】框架總覽及菜單模塊的處理
這篇文章主要介紹了基于BootStrap Metronic開發(fā)框架經(jīng)驗小結(jié)【一】框架總覽及菜單模塊的處理的相關資料,小編認為非常具有參考借鑒價值,感興趣的朋友一起學習吧2016-05-05
ES5 ES6中Array對象去除重復項的方法總結(jié)
這篇文章主要給大家介紹了Array對象去除重復項的相關資料,文中通過示例代碼詳細介紹了在ES5和ES6中Array對象去除重復項的方法,需要的朋友可以參考借鑒,下面來一起看看吧。2017-04-04
Js得到radiobuttonlist選中值的兩種方法(推薦)
下面小編就為大家?guī)硪黄狫s得到radiobuttonlist選中值的兩種方法(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08
JS動態(tài)修改表格cellPadding和cellSpacing的方法
這篇文章主要介紹了JS動態(tài)修改表格cellPadding和cellSpacing的方法,涉及javascript操作cellPadding和cellSpacing屬性的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03

