这里有两个页面,test.php和testserver.php。

test.php

<script src="scripts/jq.js" type="text/javascript"></script>
<script>
    $(function() {
        $.ajax({url:"testserver.php",
            success:function() {
                alert("Success");
            },
            error:function() {
                alert("Error");
            },
            dataType:"json",
            type:"get"
        }
    )})
</script>

testserver.php

<?php
$arr = array("element1",
             "element2",
             array("element31","element32"));
$arr['name'] = "response";
echo json_encode($arr);
?>

现在我的问题是:当这两个文件都在同一服务器(本地主机或web服务器),它的工作和警报(“成功”)被调用;如果它在不同的服务器上,即web服务器上的testserver.php和localhost上的test.php,则它不工作,并且alert(“错误”)正在执行。即使AJAX内部的URL更改为http://domain.example/path/to/file/testserver.php


当前回答

我知道3个方法来解决你的问题:

First if you have access to both domains you can allow access for all other domain using : header("Access-Control-Allow-Origin: *"); or just a domain by adding code bellow to .htaccess file: <FilesMatch "\.(ttf|otf|eot|woff)$"> <IfModule mod_headers.c> SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.net|dev02.otherdomain.net)$" AccessControlAllowOrigin=$0 Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin </IfModule> </FilesMatch> you can have ajax request to a php file in your server and handle request to another domain using this php file. you can use jsonp , because it doesn't need permission. for this you can read our friend @BGerrissen answer.

其他回答

我不得不从本地磁盘加载网页“file:///C:/test/htmlpage.html”,调用“http://localhost/getxml.php”url,并在IE8+和Firefox12+浏览器中做到这一点,使用jQuery v1.7.2 lib来最小化样板代码。在阅读了几十篇文章之后,我终于明白了。以下是我的总结。

服务器脚本(.php, .jsp,…)必须返回http响应头Access-Control-Allow-Origin: * 在使用jQuery ajax之前,在javascript中设置这个标志:jQuery.support.cors = true; 你可以设置标志一次或每次使用jQuery ajax函数 现在我可以在IE和Firefox中阅读。xml文档。其他浏览器我没有测试。 响应文档可以是纯/文本,xml, json或其他任何东西

下面是一个jQuery ajax调用的例子,其中包含一些调试系统。

jQuery.support.cors = true;
$.ajax({
    url: "http://localhost/getxml.php",
    data: { "id":"doc1", "rows":"100" },
    type: "GET",
    timeout: 30000,
    dataType: "text", // "xml", "json"
    success: function(data) {
        // show text reply as-is (debug)
        alert(data);

        // show xml field values (debug)
        //alert( $(data).find("title").text() );

        // loop JSON array (debug)
        //var str="";
        //$.each(data.items, function(i,item) {
        //  str += item.title + "\n";
        //});
        //alert(str);
    },
    error: function(jqXHR, textStatus, ex) {
        alert(textStatus + "," + ex + "," + jqXHR.responseText);
    }
});

你可以通过添加Access-Control-Allow-Origin来控制HTTP头。将其设置为*将接受来自任何域的跨域AJAX请求。

使用PHP真的很简单,只需在脚本中添加以下一行,你想要从你的域访问外部:

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

不要忘记在httpd.conf中启用mod_headers模块。

使用JSONP。

jQuery:

$.ajax({
     url:"testserver.php",
     dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
     success:function(json){
         // do stuff with json (in this case an array)
         alert("Success");
     },
     error:function(){
         alert("Error");
     }      
});

PHP:

<?php
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");";
?>

echo可能是错误的,我已经有一段时间没用php了。在任何情况下,你都需要输出callbackName('jsonString'),注意引号。jQuery会传递自己的回调名称,所以你需要从get参数中获取。

正如Stefan Kendall所发布的,$.getJSON()是一个简便方法,但随后你需要附加'callback=?'到url作为GET参数(是的,值是?,jQuery用自己生成的回调方法替换它)。

Jquery文档(链接):

由于浏览器的安全限制,大多数“Ajax”请求都遵循同源策略;请求无法成功地从不同的域、子域或协议检索数据。 脚本和JSONP请求不受同源策略限制。

因此,我认为您需要使用jsonp来处理请求。但我自己还没试过。

我使用Apache服务器,所以我使用mod_proxy模块。使模块:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

然后添加:

ProxyPass /your-proxy-url/ http://service-url:serviceport/

最后,将proxy-url传递给脚本。