zoukankan      html  css  js  c++  java
  • AJAX跨域问题总结

    跨域是什么?

    首先说下同源,同源策略是浏览器的一种安全策略,所谓同源是指,域名,协议,端口完全相同。而跨域就是不同源 !

    能够进行跨域的请求

    一般a,img,link[rel=stylesheet],video,audio,等等能够发出请求的标签都可以实现跨域访问。但是这些标签不能得到返回的东西,所以一般不会用他们来请求资源。

    常见的跨域处理方案:

    由于ajax先天设计的时候,不能实现跨域访问。所以就出现了处理跨域这样的问题。 
    ① jsonp来处理跨域,下面用jQuery来实现,关键代码如下:

    $.ajax({
      type : "GET",
      url : "http://www.a.com/index.php?message=msg&callback=?",
      dataType : "jsonp",
      jsonp: 'callback',
      success : function(json){
          console.log(json.msg);
      }
    });

    ② 服务端设置 Access-Control-Allow-Origin 
    我们使用nodejs来完成这一问题。服务端代码如下:

    "use strict"
    const http = require('http');
    const server = http.createServer();
    
    server.on('request',(req,res)=>{
        res.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"});
        res.write('ajax cross domain');
        res.end();
    })
    
    server.listen(3000,(err)=>{
      if(err){
        return console.log(err.message);
      }
      console.log('server is on');
    })

    浏览器端代码如下:

    window.onload = function(){
      var xhr = new XMLHttpRequest();
      xhr.open("post","http://localhost:3000/");
      xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
              console.log(xhr.responseText);
            }
        }
      }
      xhr.send(null);
    }

    使用http的形式访问客户端网页,那么就会输出不同源下返回的数据。 
    ③ 其他跨域策略 iframe, window.postMessage()等 
    详见: http://rickgray.me/2015/09/03/solutions-to-cross-domain-in-browser.html

    ④ 使用豆瓣的api,简单封装一个跨域请求函数:

    <script>
        /* 封装数据  跨域url  params fn */
        function crossDomain(url,params,fn){
            var head = document.getElementsByTagName('head')[0];
            // 1. 处理回调函数
            var cbName = 'jsonp'+ (Math.random() * Math.random()).toString().substr(2) + new Date().getTime();
            /* 将回调函数挂载到window对象上 */
            window[cbName] = function(data){
                // 拿到并处理数据
                fn(data);
                // 拿到数据后remove掉
                //head.removeChild(scriptObj);
            }
            // 2. 解析url
            var qstring = '';
            for(var key in params){
                qstring += key + '=' + params['key'] + '&';
            }
            qstring += 'callback=' + cbName;
            url += '?' + qstring;
            // 3. 插入script
            var scriptObj = document.createElement('script');
            scriptObj.src = url;
            head.appendChild(scriptObj);
        }
    </script>
    
    <script>
        /*  使用  */
        crossDomain('http://api.douban.com/v2/movie/in_theaters',{},function(data){
            console.log(data);
        })
    </script>
    知识无止境,追其宗,而归一
  • 相关阅读:
    如何将网格式报表打印成其它样式
    拥有与实力不相称的脾气是种灾难——北漂18年(23)
    8.8.1 Optimizing Queries with EXPLAIN
    mysql 没有rowid 怎么实现根据rowid回表呢?
    secondary index
    8.5.5 Bulk Data Loading for InnoDB Tables 批量数据加载
    mysql 中key 指的是索引
    8.5.4 Optimizing InnoDB Redo Logging 优化InnoDB Redo 日志
    8.5.3 Optimizing InnoDB Read-Only Transactions 优化InnoDB 只读事务
    8.5.1 Optimizing Storage Layout for InnoDB Tables InnoDB表的存储布局优化
  • 原文地址:https://www.cnblogs.com/bluesky1024/p/6296046.html
Copyright © 2011-2022 走看看