今天在做web的跨源请求数据的时候,遇到了问题,本人使用IE10可以直接使用dojo/_base/xhr进行跨源请求,但是使用firefox的时候竟然报错,错误信息如下
require(["dojo/_base/xhr"], lang.hitch(this, function(xhr){
xhr.get({
url: "url,
preventCache: true,
content: {},
timeout: 100000,
load: lang.hitch(this, function(response){
var json = dojo.fromJson(response);
//TODO
}),
error: dojo.hitch(this, function(response, ioArgs){
})
});
按照上面的写法,在firefox中就报了上面的那个错误,如果用jQuery的getJson不管是IE或者是firefox都没有问题,最后只能求助Google,在翻上越岭之后,终于发现了一条有用的信息,就是在xhr的请求头加入
headers: {
"X-Requested-With": null//跨源请求数据需要添加此项
}
就解决了问题。
至于原理还不是很明白,如果有什么错误或解释大家可以回复。
问题补充:
前台js部分如上设置后,后台在接收请求的时候需要添加如下代码,红色部分
java代码:
@RequestMapping(value="/yourFunc")
public void yourFunc(HttpServletRequest req, HttpServletResponse resp) throws Exception {
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
resp.getWriter().println(JSONObject.fromObject(null));
}