我正在尝试执行跨域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中运行良好。我正在使用IE 8.0和Firefox 8。
除了requestHeaders
之外,我还需要添加其他内容吗?
捕获的Http Headers如下,即使这样,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
答案 0 :(得分:0)
我面临同样的问题。
这是我到目前为止所发现的:
https://developer.mozilla.org/En/Using_XMLHttpRequest
(Firefox 3之前的Firefox版本允许您将首选项capability.policy..XMLHttpRequest.open设置为allAccess,以便为特定站点提供跨站点访问权限。不再支持此功能。)
http://en.wikipedia.org/wiki/XMLHttpRequest#Cross-domain_requests
希望这会有所帮助......
答案 1 :(得分:0)
您正尝试向请求发送“Access-Control-Allow- *”标头。
相反,您的服务器应该回复这些标题。
CORS(预检)以这种方式运作:
浏览器要求服务器发送请求权限:访问控制请求 - * 标头(浏览器会在您尝试执行跨域请求时自动添加它们)
服务器以 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
* Connected to someotherdomain port 8080 (#0) > OPTIONS /imghtml?img=100 HTTP/1.1 > User-Agent: curl/7.30.0 > Host: someotherdomain:8080 > Accept: */* > Origin: http://myserver > Access-Control-Request-Methods: GET > Access-Control-Request-Headers: X-Requested-With > < HTTP/1.1 200 OK < Date: Wed, 08 May 2013 14:34:45 GMT < Access-Control-Allow-Origin: * < Access-Control-Allow-Headers: X-Requested-With < Access-Control-Allow-Methods: GET < Access-Control-Max-Age: 86400 < Content-Length: 0 < Content-Type: text/plain < * Connection #0 to host someotherdomain left intact
如果您不想将任何自定义标头发送到服务器。然后只需删除 Access-Control-Allow-Headers:行