JavaScript之跨域问题

零到壹度
零到壹度 原创
2018-04-11 16:09:15 1124浏览

本篇文章给大家分享的内容是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('//m.sbmmt.com/m/')) + "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" 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之跨域问题的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。