ajax跨域访问会遇到这个异常:
XMLHttpRequest cannot load http://10.43.15.23/hnsh/rest/waterInfo/getRiverInfo.do. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
通常的做法是用服务器(tomcat java)去跳转请求:
public static String getJson(String url) {
String path = url;
List list = new ArrayList();
String content = "";// 读取url内容
Set set = new HashSet();
try {
URL cumtURL = new URL(path);
URLConnection cumtConnection = cumtURL.openConnection();
DataInputStream din = new DataInputStream(cumtConnection.getInputStream());
String inputLine="";
while ((inputLine = din.readLine()) != null) {
content += inputLine;
}
content = new String(content.getBytes("ISO-8859-1"), "UTF-8").trim();
din.close();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return content;
}
页面里这样(jquery):
$("#b2").click(function(){
$.getJSON("http://ip:8080/hnsh/rest/getInfo.do",function(data,status){
alert("数据: " + data.list.length + "\n状态: " + status);
});
});
如果用 jsonp做直接跨域的话需要在url后面加上:yoururl?callback=?,jquery原生支持,
页面里这样(jquery):
$("#b2").click(function(){
$.getJSON("http://10.43.15.23/hnsh/rest/waterInfo/getRiverInfo.do<strong><span style="color:#ff6666;">?callback=?</span></strong>",function(data,status){
alert("数据: " + data.list.length + "\n状态: " + status);
});
});
这样子的话仍需要修改服务器,以支持callback;详见(详见:http://www.ibm.com/developerworks/cn/web/wa-aj-jsonp1/)
否则虽然请求到了异域的数据,但会解析错误:
Uncaught SyntaxError: Unexpected token :
还有一种方式,关闭浏览器可跨域安全限制,即“disable web security”页面和服务器啥代码都不动:
以firefox为例,装一个扩展组件就可以了:
扩展地址:http://spenibus.net/files/gitbin/cors-everywhere-firefox-addon/
重启浏览器在定制里启用该扩展:
找到这个组件,拖到搜索栏后面,单击启用就行了,从此和跨域限制说拜拜了: