首页 > 代码库 > 解决Ajax跨域问题:Origin xx is not allowed by Access-Control-Allow-Origin.

解决Ajax跨域问题:Origin xx is not allowed by Access-Control-Allow-Origin.

解决Ajax跨域问题:Origin xx is not allowed by Access-Control-Allow-Origin.

今天一个Ajax跨域问题,纠结我半天,记录之。 

<html><head>    <title>title</title>    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>    <script>        $.ajax({            url:"http://map.yanue.net/gpsApi.php?lat=22.502412986242&lng=113.93832783228",            type:GET,            success: function(data){                $(body).append( "Name: " + data );            }        });    </script></head><body>    测试Ajax跨域问题</body></html>

没有结果,chrome用F12 下查看错误 得知:XMLHttpRequest cannot load http://map.yanue.net/gpsApi.php?lat=22.502412986242&lng=113.93832783228. Origin http://localhost is not allowed by Access-Control-Allow-Origin. AJAX跨域问题产生。

搜了好久,得知解决方案:

一:使用jsonp格式, 如jquery中ajax请求参数   dataType:‘JSONP‘。(可选)

<html><head>    <title>title</title>    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>    <script>        $.ajax({            url:"http://map.yanue.net/gpsApi.php?lat=22.502412986242&lng=113.93832783228",            type:GET,            dataType:JSONP,            success: function(data){                $(body).append( "Name: " + data );            }        });    </script></head><body>测试Ajax跨域问题</body></html>

 

二,server端加上header设为 Access-Control-Allow-Origin:*

getHttpServletResponse().setHeader("Access-Control-Allow-Origin", "*"); // 跨域处理

问题就解决了。

 

 

 

感谢:   http://yanue.net/post-130.html

 

解决Ajax跨域问题:Origin xx is not allowed by Access-Control-Allow-Origin.