1. 程式人生 > >跨域AJAX請求

跨域AJAX請求

ava content script supported allow header href min oca

在處理跨域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請求