跨域xmlhttp

发布于 2024-11-17 11:00:39 字数 1248 浏览 3 评论 0原文

我正在编写这个 javascript,它将在其他几个域中使用,这些域调用 php 脚本(仅在我的域上)来返回数组。我正在使用 xmlhttp,在我的域上测试时它效果很好,但是一旦从单独的域放置或调用 javascript,它就会完全崩溃。有人知道如何跨域请求吗?

注意:我必须执行一个奇怪的小技巧,以允许我进行两个单独的调用,并确保它们在处理之前都被返回。无论如何,这每次在我的域上都运行得很好。

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

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();

}

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.

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();

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

放肆 2024-11-24 11:00:39

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

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

如果您想允许所有域而不是白名单,

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

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

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

初见 2024-11-24 11:00:39

其原因是同源政策。它的目的是阻止恶意脚本访问其他网站的敏感数据。您应该考虑编写 JSONP 请求作为您的问题的解决方法。

The reason for this is the same origin policy. It was put in place to stop malicious scripts from accessing sensitive data from other websites. You should look into writing a JSONP request as a workaround for your problem.

情未る 2024-11-24 11:00:39

我去年开始创建一个持续社区维基,它解释了许多方法规避同源政策。最有可能在那里找到适合您情况的解决方案。

There's an ongoing community wiki I started last year that explains many ways of circumventing the same origin policy. A solution that fits your situation can most likely be found there.

不醒的梦 2024-11-24 11:00:39

和其他的一样,都是同源政策造成的。
假设页面位于“a.com”,无论 JavaScript 文件在哪里,
只要使用XMLHttpRequest方式,就只能访问a.com的数据。
即使子域 aacom 也无法访问 a.com。

您可以有 2 个选项:

1) 使用

function getUrl(url) {
    var scriptEl = document.createElement("script");
    scriptEl.src = url;
    scriptEl.async = true;
    document.getElementsByTagName("head")[0].appendChild(scriptEl);
}
// Predefined callbacks
window.companyCallback = function (responseData) {
    parsedJSONCompanies = responseData;
};
window.urlCallback = function (responseData) {
    parseJSONurls = responseData;
};
getUrl("http://mydomain.com/connect.php?q=companies");
getUrl("http://mydomain.com/connect.php?q=urls");

当然你也必须修改你的PHP以满足需要。

<?php
header("content-type: application/json");
if ($_GET['q'] === "urls")
{
    echo "companyCallback(";
    json_encode($result);
    echo ");";
}
else
{
    echo "urlCallback(";
    json_encode($result);
    echo ");";
}
?>

2) 将 proxy.php 放在不同的域中
以上方法是我推荐的。
如果您不想大量修改代码,请改用代理技术。
您必须具有在不同主机上添加 proxy.php 的权限。
内容如下:

<?php
$url = "http://mydomain.com/connect.php?q=" . $_GET["q"];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
?>

注意:注意安全问题,需要检查请求来自哪里。

在 JavaScript 中,您只需将 xmlhttp.open() 中的 url 指向同一个 PHP 域。

xmlhttp.open("proxy.php?q=urls", true);

希望有帮助。

Same with others, it's caused by same origin policy.
Suppose page is at "a.com", no matter where JavaScript file is,
As long as you use XMLHttpRequest approach, you can only access data from a.com.
Even subdomain a.a.com can't access a.com.

You can have 2 options:

1) Use <script/> tag hack
JSONP is great, but it seems you don't rely on any library.
It's a JavaScript nature you can include JavaScript locating on other domain.
<script/> tag hack is a simple technique which dynamically create and append <script/> node.
And its src attribute is the URL which is in different domain.

function getUrl(url) {
    var scriptEl = document.createElement("script");
    scriptEl.src = url;
    scriptEl.async = true;
    document.getElementsByTagName("head")[0].appendChild(scriptEl);
}
// Predefined callbacks
window.companyCallback = function (responseData) {
    parsedJSONCompanies = responseData;
};
window.urlCallback = function (responseData) {
    parseJSONurls = responseData;
};
getUrl("http://mydomain.com/connect.php?q=companies");
getUrl("http://mydomain.com/connect.php?q=urls");

Of course you also have to modify your PHP to meet the need.

<?php
header("content-type: application/json");
if ($_GET['q'] === "urls")
{
    echo "companyCallback(";
    json_encode($result);
    echo ");";
}
else
{
    echo "urlCallback(";
    json_encode($result);
    echo ");";
}
?>

2) Place proxy.php in different domain
The above method is what I recommended.
If you don't want to revamp your code heavily, use proxy technique instead.
You must have privilege to add a proxy.php on different hosts.
The content like this:

<?php
$url = "http://mydomain.com/connect.php?q=" . $_GET["q"];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
?>

NOTE: Be careful about security issue, you need to check where the request from.

In JavaScript, you just need to point the url in xmlhttp.open() to this same domain PHP.

xmlhttp.open("proxy.php?q=urls", true);

Hope it helps.

帝王念 2024-11-24 11:00:39

就像其他人所说的那样,您可以使用 JSON-p ),或者如果浏览器支持(新 A -分级浏览器这样做) CORS 你可以用它来代替。

Like others said you could use JSON-p) for that or if the browsers supports(new A-graded browsers do) CORS you could use that instead.

本王不退位尔等都是臣 2024-11-24 11:00:39

如前所述,大多数非 html5 不允许跨浏览器 ajax 请求。为了解决这个问题,我调用了一个远程 JavaScript 脚本。

添加一行

<script type="text/javascript" src="http://www.somemedomain.xxx/myjavascript.php?arg1=xxx&arg"> 

使用javascript在其他服务器上的myjavascript.php文件上

,就可以处理、收集从浏览器收集的信息。您必须将 php 文件编码为 javascript。

header( "content-type: application/javascript" ) //check php.net

这将在 ie6+ 中工作

As mentioned most non html5 dont allow cross browser ajax requests. To get around this I call a remote javascript script.

use javascript to add a line like

<script type="text/javascript" src="http://www.somemedomain.xxx/myjavascript.php?arg1=xxx&arg"> 

on the myjavascript.php file on the other server, you can process, collect information collected from the browser.

you have to encode the php file as javascript.

header( "content-type: application/javascript" ) //check php.net

This will work in ie6+

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文