js跨域

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/3464056.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" οnchange="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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值