zoukankan      html  css  js  c++  java
  • ajax解决跨域问题

    1.在介绍之前先介绍几个概念

    json:

    {
         date: "Sun Dec 24 21:44:42 CST 2017", 
         temperature: "21",
         humidity: "15"
    }

    jsonp:

    callback({
          date: "Sun Dec 24 21:44:42 CST 2017",
          temperature: "21", 
          humidity: "15"
    })

    所以在后台传数据的时候就要根据类型来传递相应的数据格式。

    2.ajax的前生今世

    大家都知道ajax不是一种新语言,而是在JS上进行封装,实现更好的对dom节点的操纵。在它的1.4版本后,对json的格式更加要求了,这里列出它对后台数据的请求:

    $.ajax({
              type: "get",
              url: "http://localhost/args",
              async: true,  
              dataType: "json",  
              success: function (data) {
                console.log(data);
              },
              error:function(){
                console.log("fail");
              }
         });

    如果你用上面的方式请求你的接口,出现这样的问题:

    No 'Access-Control-Allow-Origin' header is present on the requested resource.

    你网上搜了一下,把dataType: "json"改为“jsonp”,如果你的问题彻底解决了,那恭喜你,如果你只是在chrome控制台看不到这个错误了,但是数据明明可以在通过URL获取到,但是就是不进入success: function(data){}方法中,而是执行error中的语句。你网上又搜了一下,找到了原因是ajax在1.4版本对json的格式严格,你看了看,自己的json格式是完全准确的,但为什么还是执行error方法中的语句?

    这里就要看看我在1中说的概念,你把dataType改成“jsonp”,你就得在服务端把数据改成jsonp的格式,这时候你的问题算是彻底解决了。

    但是你发现你的服务端的数据格式不是说改就能改的,你又陷入了沉思。。。。。问题相当于没解决,又回到起点。MLGB

    3.服务端的解决方案

    如果你用的SpringBoot,那么问题就好解决了,你需要在你的Controller目录加上这个:

    import org.springframework.context.annotation.Configuration;    
    import org.springframework.web.servlet.config.annotation.CorsRegistry;    
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;    
      
    @Configuration    
    public class CorsConfig extends WebMvcConfigurerAdapter {    
      
        @Override    
        public void addCorsMappings(CorsRegistry registry) {    
            registry.addMapping("/**")    
                    .allowedOrigins("*")    
                    .allowCredentials(true)    
                    .allowedMethods("GET", "POST", "DELETE", "PUT")    
                    .maxAge(3600);    
        }    
      
    } 

    问题就解决了。

    如果你用的是MVC的框架或者你没用框架,那么问题也好解决,大家在服务器返回数据的时候借助工具来JSON化数据。

    4.闲聊

    jsonp和服务器端改变数据的类型都可以解决问题。

    我们来说说他们的优缺点,前一种只能get,且数据格式不是标准的json格式,解决问题治标不治本,后一种没什么缺点

    --------2017.12.24    兰州

    平安夜,祝愿全世界的人都平平安安

  • 相关阅读:
    According to TLD or attribute directive in tag file, attribute end does not accept any expressions
    Several ports (8080, 8009) required by Tomcat v6.0 Server at localhost are already in use.
    sql注入漏洞
    Servlet—简单的管理系统
    ServletContext与网站计数器
    VS2010+ICE3.5运行官方demo报错----std::bad_alloc
    java 使用相对路径读取文件
    shell编程 if 注意事项
    Ubuntu12.04下eclipse提示框黑色背景色的修改方法
    解决Ubuntu环境变量错误导致无法正常登录
  • 原文地址:https://www.cnblogs.com/huhu1203/p/8099780.html
Copyright © 2011-2022 走看看