• 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>
    知识无止境,追其宗,而归一
  • 相关阅读:
    重读APUE(7)-link/unlink与mkdir/rmdir
    重读APUE(6)-umask
    社交系统中用户好友关系数据库设计
    修改Web项目的名称后,在TomCat中部署项目,项目的名称还是与原来相同的解决方案
    域名解析TTL是什么意思 TTL值设置为多少合适?
    mysql权限控制—新建用户允许其远程连接
    毕业设计技术方向(转载)
    统一资源定位符URL的组成
    开发中model,entity和pojo的区别
    要不要签三方协议
  • 原文地址:https://www.cnblogs.com/bluesky1024/p/6296046.html
Copyright © 2020-2023  润新知