我正在尝试制作跨域跨浏览器.js请求(没有任何libs)。
var isIE8 = window.XDomainRequest ? true : false;
var invocation = createCrossDomainRequest();
var url = 'http://someserver.com/cgi-bin/targets.cgi?sid=';
function createCrossDomainRequest(url, handler)
{
var request;
if (isIE8)
{
request = new window.XDomainRequest();
}
else
{
request = new XMLHttpRequest();
}
return request;
}
function sendTarget(sid,target)
{
if (invocation)
{
var phone_id = getCookie('phone_cookie');
url = url + sid +'&target='+target+'&phone_id='+phone_id+'&url='+encodeURIComponent(document.URL);
if(isIE8)
{
invocation.onload = outputResult;
invocation.open("GET", url, true);
invocation.send();
}
else
{
invocation.open('GET', url, true);
invocation.onreadystatechange = handler;
invocation.send();
}
}
else
{
var text = "No Invocation TookPlace At All";
}
}
function handler(evtXHR)
{
if (invocation.readyState == 4)
{
if (invocation.status == 200)
{
outputResult();
}
else
{
var text = "Invocation Errors Occured";
}
}
}
function outputResult()
{
var response = invocation.responseText;
}
它在IE中起作用,但Mozilla和Chrome不起作用。这些浏览器正在获取错误"调用错误发生"。invocation.status为零。访问控制 - 允许原素设置为 *。
我需要做什么来解决这个问题?
我不能使用任何库,只需清洁JS(技术问题)即可。没有jQuery!此代码需要在许多客户端网站上(不是一个或两个)。我不需要得到答复,只需要发送请求即可。而且我没有在xmlhttprequest上循环 - 有什么想法?
我已经采用了您在上面提供的代码,并将其修改为更为通用。但是,您应该能够将其更改为适合。以下代码在Chrome和Firefox中起作用:
var isIE8 = window.XDomainRequest ? true : false;
var url = 'http://www.phobos7.co.uk/research/xss/simple.php';
var resultText = '';
var invocation = createCrossDomainRequest();
makeRequest();
function createCrossDomainRequest(url, handler) {
var request;
if (isIE8) {
request = new window.XDomainRequest();
} else {
request = new XMLHttpRequest();
}
return request;
}
function makeRequest() {
if (invocation) {
if (isIE8) {
invocation.onload = requestSucceeded;
invocation.open("GET", url, true);
invocation.send();
} else {
invocation.open('GET', url, true);
invocation.onreadystatechange = handler;
invocation.send();
}
} else {
resultText = "No Invocation TookPlace At All";
}
}
function handler(evtXHR) {
if (invocation.readyState == 4) {
if (invocation.status == 200) {
requestSucceeded();
} else {
resultText = "Invocation Errors Occured";
}
}
}
function requestSucceeded() {
resultText = invocation.responseText;
outputResult();
}
function outputResult() {
document.getElementById( 'output' ).innerHTML = resultText;
}
您可以在此处进行测试:http://jsfiddle.net/leggetter/3qfqe/
该站点的响应标头 - 允许CORS - 是:
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Type:text/html
Date:Wed, 12 Feb 2014 22:48:37 GMT
Keep-Alive:timeout=5, max=100
Server:Apache
Transfer-Encoding:chunked
X-Powered-By:PHP/5.3.24
仅需要Access-Control-Allow-Origin:*
。
如果您使用上面的JavaScript并确保设置Access-Control-Allow-Origin:*
标头,则可以从JavaScript发出跨域请求。