美文网首页
解决springmvc4的ajax跨域问题

解决springmvc4的ajax跨域问题

作者: Bruce杨 | 来源:发表于2017-12-19 14:36 被阅读0次
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <mvc:annotation-driven/>
        <context:component-scan base-package="com.bruce.controller"/>
        <mvc:cors>
            <mvc:mapping path="/**" allowed-origins="*" allow-credentials="true" max-age="1800"
                         allowed-methods="GET,POST,OPTIONS"/>
        </mvc:cors>
    </beans>
    

    加上

        <mvc:cors>
            <mvc:mapping path="/**" allowed-origins="*" allow-credentials="true" max-age="1800"
                         allowed-methods="GET,POST,OPTIONS"/>
        </mvc:cors>
    

    就可以了
    原生的js访问本地接口(通过ajax)

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <script>
            function push(){
                 var xmlhttp;
                if (window.XMLHttpRequest)
                {
                    //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
                    xmlhttp=new XMLHttpRequest();
                }
                else
                {
                    // IE6, IE5 浏览器执行代码
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange=function()
                {
                    if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        document.getElementById("pushStatus").innerHTML='发送成功:返回内容是 '+xmlhttp.responseText;
                    }
                }
                // xmlhttp.dataType='JSONP';
                xmlhttp.open("GET","http://127.0.0.1:9010/push",true);
                // xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");//缺少这句,后台无法获取参数
                xmlhttp.send();
            }
        </script>
    </head>
    <body>
    
    <div id="pushStatus">
    </div>
    <button onclick="push()">发送推送</button>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:解决springmvc4的ajax跨域问题

          本文链接:https://www.haomeiwen.com/subject/fwgbwxtx.html