最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

JavaScript之跨域问题

来源:动视网 责编:小采 时间:2020-11-27 19:55:55
文档

JavaScript之跨域问题

JavaScript之跨域问题:本篇文章给大家分享的内容是JavaScript之跨域问题,有着一定的参考价值,有需要的朋友可以参考一下1jsonp一般接口使用jsonp跨域,使用jquery的ajax指定dataType为jsonp即可$.ajax({ async : true, url : "https://api.do
推荐度:
导读JavaScript之跨域问题:本篇文章给大家分享的内容是JavaScript之跨域问题,有着一定的参考价值,有需要的朋友可以参考一下1jsonp一般接口使用jsonp跨域,使用jquery的ajax指定dataType为jsonp即可$.ajax({ async : true, url : "https://api.do


本篇文章给大家分享的内容是JavaScript之跨域问题,有着一定的参考价值,有需要的朋友可以参考一下

1jsonp

一般接口使用jsonp跨域,使用jquery的ajax指定dataType为jsonp即可

$.ajax({
 async : true,
 url : "https://api.douban.com/v2/book/search",
 type : "GET",
 dataType : "jsonp", // 返回的数据类型,设置为JSONP方式
 jsonp : 'callback', //指定一个查询参数名称来覆盖默认的 jsonp 回调参数名 callback
 jsonpCallback: 'handleResponse', //设置回调函数名
 data : {
 q : "javascript",
 count : 1
 },
 success: function(response, status, xhr){
 console.log('状态为:' + status + ',状态是:' + xhr.statusText);
 console.log(response);
 }
 });

jsonp支持跨域的原理:JSONP实现跨域请求的原理简单的说,就是动态创建<script>标签,然后利用<script>的src 不受同源策略约束来跨域获取数据。

其实就是下面的代码的实现方式:js脚本返回callback(data),页面中定义一个callback函数

<script type="text/javascript">
 function handleResponse(response){
 console.log(response);
 }
</script>
<script type="text/javascript">
 window.onload = function() {

 var oBtn = document.getElementById('btn');

 oBtn.onclick = function() { 

 var script = document.createElement("script");
 script.src = "https://api.douban.com/v2/book/search?q=javascript&count=1&callback=handleResponse";
 document.body.insertBefore(script, document.body.firstChild); 
 };
};
</script>

2iframe + form 兼容IE浏览器,iframe的body内容是要用的数据

<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
 <form id="fileform" method="post" enctype="multipart/form-data" target="hidden_frame">
 <input type="file" name="fileUpload" />
 </form>
 <button id="submitbtn">开始上传</button>
 <script type="text/javascript">
 function callback(msg) {
 //回调函数
 alert(msg);
 }
 </script>
 <script type="text/javascript">
 $("#submitbtn").click(function() {
 var callbackurl = window.location.href.substring(0, window.location.href.lastIndexOf('/')) + "proxy.html"; //获取代理文件路径
 $("#fileform").attr("action", "FileHandler.ashx?callbackurl=" + callbackurl);
 $("#fileform").submit();
 })
 </script>

3H5的postMessage()方法,兼容性没那么好

详细见https://www.cnblogs.com/dolphinX/p/34056.html

上传图片代码,接口返回的数据就是postMessage的写法

<form action='http://bird.sns.iqiyi.com/group_photo/upload' method="post" target="imgFile"
 id="fileinfo" enctype="multipart/form-data">
 <input type="file" id="imgFile" accept="image/gif, image/png" class="hide" onchange="getPhotoSize(this)"
 />
 <input type="hidden" name="name" value="" />
 <input type="hidden" name="hobby" value="" />
 </form>
 <iframe
<script type="text/javascript">
 $(document).ready(function() {
 $('#upload').click(function() {
 $("#imgFile")[0].click();
 });
 });
 var queryToJson = function(url) {
 url = url.replace(/#.*/, "");
 var query = url.substr(url.lastIndexOf('?') + 1);
 var params = query.split('&');
 var result = {};
 for (var i = 0; i < params.length; i++) {
 var t = params[i].split("=");
 if (!t[0]) continue;
 result[decodeURIComponent(t[0])] = decodeURIComponent(t[1] || "");
 }
 return result;
 };
 $('[name=name]').val(queryToJson(window.location.href).name);
 $('[name=hobby]').val(queryToJson(window.location.href).hobby);
 //判断照片大小
 function getPhotoSize(obj) {
 photoExt = obj.value.substr(obj.value.lastIndexOf(".")).toLowerCase(); 
 //只支持jpg,png
 if (photoExt != '.jpg' && photoExt != '.png') {
 showMsg("请上传正确的图片格式,如JPEG、PNG");
 return false;
 }
 var fileSize = 0;
 fileSize = obj.files[0].size;
 fileSize = Math.round(fileSize / 1024); //单位为KB
 if (fileSize >= 10000) {
 showMsg("建议上传图片不超过10M");
 return false;
 }
 //跳转到过渡页,请求上传接口,将接口返回插入结果页src
 $('#page2').addClass('hide');
 $('#imgFile').addClass('hide');
 $('#fileinfo').submit();
 $('#loading').removeClass('hide');
 getMsg();
 }
 //获取返回数据
 function getMsg() {
 window.addEventListener('message',
 function(e) {
 $('#loading').addClass('hide');
 if (e.source != window.parent) return;
 if (e.data.code == 'A00000') {
 $('#imgSrc')[0].src = e.data.data.url;
 $('#msg').html(e.data.data.message);
 $('#page5').removeClass('hide');
 } else {
 location.href = '/anotherTry.html';
 }
 },
 false);
 }
 //显示提示信息
 function showMsg(msg) {
 var _this = this;
 $('#msgTip').html(msg);
 $('#msgTip').removeClass('hide');
 window.setTimeout(function() {
 $('#msgTip').addClass('hide');
 },
 3000);
 }
 //再试一次
 function tryAgain() {
 $('#fileinfo').submit();
 $('#page5').addClass('hide');
 //看不到加载页面,页面闪
 $('#loading').removeClass('hide');
 getMsg();
 }
 </script>

文档

JavaScript之跨域问题

JavaScript之跨域问题:本篇文章给大家分享的内容是JavaScript之跨域问题,有着一定的参考价值,有需要的朋友可以参考一下1jsonp一般接口使用jsonp跨域,使用jquery的ajax指定dataType为jsonp即可$.ajax({ async : true, url : "https://api.do
推荐度:
标签: js 问题 javascript
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top