码迷,mamicode.com
首页 > Web开发 > 详细

跨域AJAX请求

时间:2017-12-13 23:54:16      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:style   localhost   cat   ade   cti   path   127.0.0.1   png   pac   

在处理跨域AJAX请求有许多方法。我这里用的是 CORS,

CORSFilter

CORSFilter是Apache官方提供一个支持CORS跨域的过滤器:

详细说明: http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html

在maven配置文件中导入依赖

<!--CORS-->
<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>2.6</version>
</dependency>    

在web.xml添加过滤器

<filter>
        <filter-name>CORS</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
        <init-param>
            <param-name>cors.allowOrigin</param-name>
            <param-value>http://127.0.0.1:8020</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedMethods</param-name>
            <param-value>POST,GET,OPTIONS,DELETE,PUT</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedHeaders</param-name>
            <param-value>Content-Type,Accept,Origin,XRequestedWith,ContentType,LastModified</param-value>
        </init-param>
        <init-param>
            <param-name>cors.exposedHeaders</param-name>
            <param-value>SetCookie</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportsCredentials</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

客户端

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>跨域AJAX请求</title>
    </head>

    <body>
        <h2>跨域AJAX请求</h2>
        <button type="button" id="btnAjax">ajax请求</button>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
        <script type="text/javascript">
            $("#btnAjax").click(function() {
                $.get("http://localhost:8080/mvc02/users", "", function(data) {
                    console.log(JSON.stringify(data));
                }, "json");
            });
        </script>
    </body>

</html>

 

服务器(本人用的是Spring MVC):

@RestController
@RequestMapping(path="/users")
public class UsersController {
    @Resource
    EmpService empService;

    /*查询所有*/
    @RequestMapping(path = "",method = RequestMethod.GET)
    public List seletUser(){
        return empService.findEmpList();
    }
}

结果:

技术分享图片

 

 Spring MVC4.2 及以上增加了对CORS的支持

 

跨域AJAX请求

标签:style   localhost   cat   ade   cti   path   127.0.0.1   png   pac   

原文地址:http://www.cnblogs.com/mylhy/p/8034681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!