当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript用JSONP跨域请求数据实例详解

JavaScript用JSONP跨域请求数据实例详解

2019年03月31日  | 移动技术网IT编程  | 我要评论

前言

最近因为工作需要,需要把爱词霸的每日一句引入到页面上,爱词霸向外开放了 接口返回 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),即只允许与同域下的接口交互。

同域是指:

  1. 同协议:如都是 http 或者 https
  2. 同域名:如都是 http://konghy.cn/a 或 http://konghy.cn/b
  3. 同端口:如都是 80 端口

也就是说,用户打开了页面: 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>

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

参考资料


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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网