跨域xmlhttp [英] Cross domain xmlhttp

查看:170
本文介绍了跨域xmlhttp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写这个javascript,将用于其他几个域名,调用php脚本(只在我的域)返回一个数组。我使用xmlhttp和它的工作伟大的测试在我的域,但一旦javascript被放置或从一个单独的域调用它完全打破。任何人都知道如何使这个请求跨域?

I am writing this javascript that will be used on several other domains which calls a php script(only on my domain) to return an array. I am using xmlhttp and it works great when testing on my domain, but as soon as the javascript is placed or called from a separate domain it completely breaks. Anybody know how to make this request cross-domain?

注意:我不得不执行一个奇怪的小黑客,让我做两个单独的电话,并确保他们两者在处理前返回。

Note: I had to perform a weird little hack to allow me to make two separate calls and make sure that they were both returned before processing. Anyways this does work perfectly every time on my domain.

这是javascript文件调用我的数组的php代码

This is tin the javascript file that calls my php code for the array

function getUrls(){
if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
    xmlhttp2 = new XMLHttpRequest();
}
else {
    // code for IE5 and IE6
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    // code for IE5 and IE6
    xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
        parsedJSONurls = JSON.parse(xmlhttp.responseText);
        xmlhttp2.open("GET", "http://mydomain.com/connect.php?q=companies", true);
        xmlhttp2.send();
    }
}
xmlhttp2.onreadystatechange = function(){
    if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
        parsedJSONcompanies = JSON.parse(xmlhttp2.responseText);
        runLoop(parsedJSONurls, parsedJSONcompanies);
    }
}
xmlhttp.open("GET", "http://mydomain.com/connect.php?q=urls", true);
xmlhttp.send();

}

推荐答案

尝试将此标头添加到您的connect.php文件

Try adding this header to your connect.php file

header('Access-Control-Allow-Origin: http://domain1.com, http://domain2.com');

如果您要允许所有网域而不是白名单

If you want to permit all domains instead of a whitelist

header('Access-Control-Allow-Origin: *');

https ://developer.mozilla.org/en/http_access_control

这篇关于跨域xmlhttp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆