我正在尝试做一个跨域的ajax请求,并将内容填充到我的JSP页面的div中,我使用的javascript方法如下,
function fetchImgLeads(){
var myAjax = new Ajax.Request(
'http://someotherdomain:8080/imghtml?img=100',
{ method:'GET',
parameters:{},
requestHeaders :["Access-Control-Allow-Origin","*","Access-Control-Allow-Methods","POST, GET, OPTIONS","Access-Control-Allow-Headers", "X-PINGOTHER","Access-Control-Max-Age","1728000"],
onSuccess:function(t){
alert(t.responseText.trim());
$('imagediv').update(t.responseText);
},
onFailure:function(t){
//do something
}
}
);
}
我在加载时调用这个,我在Firefox web控制台看到一个错误,说HTTP/1.1 401 Unauthorized
。同样的事情在IE中工作得很好。我用的是ie8和Firefox 8。
除了requestHeaders
,我还有什么要补充的吗?
捕获的Http头如下,即使ajax请求似乎也不起作用,
OPTIONS http://www.google.com/ HTTP/1.1
Host: www.google.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Proxy-Connection: keep-alive
Origin: http://localhost:8080
Access-Control-Request-Method: GET
Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-methods,access-control-allow-origin,access-control-max-age,x-prototype-version,x-requested-with
HTTP/1.1 405 Method Not Allowed
Content-Type: text/html; charset=UTF-8
Date: Fri, 25 Nov 2011 05:53:54 GMT
Server: GFE/2.0
Content-Length: 11819
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
我也面临同样的问题。
这是我目前所发现的:
https://developer.mozilla.org/En/Using_XMLHttpRequest(Firefox 3之前的版本允许您设置首选项功能。向allAccess开放,使特定站点可以跨站点访问。)
- 建议启用跨站点脚本的方法是在XMLHttpRequest的响应中使用Access-Control-Allow-Origin HTTP头。
http://en.wikipedia.org/wiki/XMLHttpRequest Cross-domain_requests
- 添加到服务器HTTP响应头中的头可以允许跨域请求成功。例如access - control - allow - origin: *,表示允许所有域访问服务器。Access-Control-Allow-Origin可以在所有支持跨域请求的浏览器中使用,包括Internet Explorer 8。W3C的规范定义在跨域资源共享中。
您正在尝试发送'Access-Control-Allow-*'标头请求。
相反,你的服务器应该用这些报头来回复。
CORS (preflight)是这样工作的:
-
浏览器请求服务器允许发送请求:Access-Control-Request-*报头(当您尝试跨域请求时浏览器会自动添加它们)
-
服务器响应Access-Control-Allow-*报头让浏览器知道是否允许发送真正的请求
Curl命令应该显示如下内容:
<>之前curl -v -H 'Origin: http://myserver' -X OPTIONS -H 'Access-Control-Request-Methods: GET' -H 'Access-Control-Request-Headers: X-Requested-With' http://someotherdomain:8080/imghtml?img=100之前<>之前*连接到其他域端口8080 (#0)比;选项/imghtml吗?img HTTP/1.1 = 100比;用户代理:旋度/7.30.0比;主持人:someotherdomain: 8080比;接受:*/*比;来源:http://myserver比;Access-Control-Request-Methods:比;Access-Control-Request-Headers: X-Requested-With比;& lt;Http/1.1 200 ok& lt;日期:2013年5月8日星期三14:34:45 GMT& lt;Access-Control-Allow-Origin: *& lt;Access-Control-Allow-Headers: X-Requested-With& lt;Access-Control-Allow-Methods:& lt;Access-Control-Max-Age: 86400& lt;内容长度:0& lt;内容类型:文本/平原& lt;连接#0到其他完整的主机域之前如果您对发送任何自定义头到服务器不感兴趣。然后把Access-Control-Allow-Headers: line