ajax跨域

        所有支持Javascript的浏览器都会使用同源策略这个安全策略,所以当前后端出现域名、协议、端口不同时,都需要解决跨域问题。以下提供三种ajax跨域解决方式:

1.jsonp

ajax请求时dataType:jsonp

会自动增加一个请求参数callback,响应时原本的json包含在callback中

缺点:响应时需要额外增加一层包装


2.response header

在springmvc中增加拦截器interceptor,preHeadle方法中增加response.setHeader("Access-Control-Allow-Origin", “*");允许所有域名跨域请求

缺点:对IE9之前的浏览器有不兼容现象


3.nginx

nginx设置反向代理将后台请求和前台进行统一

缺点:本机开发时需要配置nginx

原始请求:http://localhost:8080/index.html

被域名阻挡请求:http://localhost:8081/indextwo.html

将被拦截请求改写成:http://localhost:8080/api/indextwo.html

server {

      listen       8080; #监听端口

      server_name  localhost; #

     location / {

        root   html;#文件根目录

        index  index.html index.htm;#默认起始页

      }

    #解决方法

    location /api{

        rewrite ^.+api/?(.*)$    /$1    break;

        include uwsgi_params;

        proxy_pass    http://localhost:8081;

    }


ps:

当ajax要求dataType:json时,要求后台返回必须为标准的json格式,如果是字符串会进入error