这里有两个页面,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


当前回答

浏览器安全性防止ajax调用从一个域上托管的页面到另一个域上托管的页面;这就是所谓的“同源策略”。

其他回答

这是可能的,但您需要使用JSONP,而不是JSON。斯特凡的线索给你指明了方向。jQuery AJAX页面有更多关于JSONP的信息。

Remy Sharp有一个使用PHP的详细示例。

我使用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传递给脚本。

我知道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.

同源策略确实阻止了JavaScript跨域发起请求,但是CORS规范只允许您正在寻找的那种API访问,并且得到当前一批主要浏览器的支持。

查看如何为客户端和服务器启用跨源资源共享:

http://enable-cors.org/

“跨域资源共享(CORS)是一个实现跨域边界真正开放访问的规范。如果你提供公共内容,请考虑使用CORS将其开放给通用JavaScript/浏览器访问。”

有一些使用JSONP的例子,其中包括错误处理。

但是,请注意,使用JSONP时不会触发错误事件!参见:http://api.jquery.com/jQuery.ajax/或jQuery ajax请求使用jsonp错误