ajax跨域访问及其解决方案

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax跨域访问及其解决方案相关的知识,希望对你有一定的参考价值。

用ajax方式请求别的网站,就会发生跨域请求问题,

XMLHttpRequest cannot load http://google.com/.
No ‘Access-Control-Allow-Origin‘ header is present on the requested resource.
Origin ‘http://run.jsbin.io‘ is therefore not allowed access.

编一个服务器端servlet测试一下

    @RequestMapping("/haha")
    @ResponseBody
    String haha(String haha, HttpServletRequest req, HttpServletResponse resp) {
        //resp.addHeader("Access-Control-Allow-Origin", "null");
        System.out.println(haha);
        System.out.println("you accessed!!!");
        return haha + " : " + req.getMethod();
    }

我用的是spring mvc,如果RequestMapping不带参数,默认为‘/‘,如果请求找不到,那就去找它.

无参数的RequestMapping只允许有一个,否则无法部署,报错.

在spring mvc中,如果没有规定请求方式,默认是都可以,无论是get还是post都能够找到资源,只要url正确就行.

下面用ajax请求这个servlet

<body>
    <h1 id=‘resp‘></h1> 
        <input id=‘haha‘ type=‘text‘></input> 
</body>
<script type="text/javascript">
    $(#haha).keydown(function(event) {
        console.log(event.which)
        if(event.which==13){
            $.get(http://localhost:8080/news/haha,{haha:wyf},function(data){
                console.log(data)
                console.log(get over)
            })
        }
    });
</script>

服务器端输出了"you succeed!!!",这说明对于跨域请求服务器是搭理了的,问题出在服务器禁止返回或者是浏览器不允许用户查看返回的内容.

据我猜测,很有可能是后者,即:chrome分析返回结果,发现跨域了,于是不让用户看了.

解决方案很简单:编一个表单进行提交,因为只有ajax才存在跨域访问问题,而提交表单跟ajax不一样.

提交表单之后服务器端决定了浏览器端页面的跳转,把权力完全交给了服务器,而ajax只是通过服务器获取数据

下面的表单是可以提交成功的

    <form action=‘http://localhost:8080/news/haha‘ method="GET">
        <input id=‘haha‘ type=‘text‘></input>
        <input type="submit"></input>
    </form>

可是填写表单太麻烦,于是可以虚拟表单并提交

    $(document).ready(function(){
        var form=$(‘<form></form>‘)
        $(form).attr({"action":‘http://localhost:8080/news/haha‘,"method":‘post‘}).append("<input name=‘haha‘ value=‘haha weidiao‘>")
        $(form).submit()
        console.log(‘haha‘)
    })

 

以上是关于ajax跨域访问及其解决方案的主要内容,如果未能解决你的问题,请参考以下文章

Ajax 跨域问题及其解决方案

跨域问题解决方法

ajax跨域访问数据

ajax跨域访问解决方案

ajax跨域原理以及解决方案

win10的Edge不支持AJAX跨域访问吗?