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


当前回答

JSONP是一个不错的选择,但是还有一种更简单的方法。您可以简单地在服务器上设置Access-Control-Allow-Origin标头。将其设置为*将接受来自任何域的跨域AJAX请求。(https://developer.mozilla.org/en/http_access_control)

当然,这样做的方法因语言而异。下面是Rails版本:

class HelloController < ApplicationController
  def say_hello
    headers['Access-Control-Allow-Origin'] = "*"
    render text: "hello!"
  end
end

在本例中,say_hello动作将接受来自任何域的AJAX请求,并返回“hello!”响应。

下面是它可能返回的头的一个例子:

HTTP/1.1 200 OK 
Access-Control-Allow-Origin: *
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: text/html; charset=utf-8
X-Ua-Compatible: IE=Edge
Etag: "c4ca4238a0b923820dcc509a6f75849b"
X-Runtime: 0.913606
Content-Length: 6
Server: WEBrick/1.3.1 (Ruby/1.9.2/2011-07-09)
Date: Thu, 01 Mar 2012 20:44:28 GMT
Connection: Keep-Alive

尽管它很简单,但它确实有一些浏览器限制。看到http://caniuse.com/壮举=歌珥。

其他回答

我知道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。的 策略允许运行脚本 来自同一站点的页面 访问彼此的方法和 没有特定的属性 限制,但阻止访问 大多数方法和属性 不同网站的页面。

为了让你能够获得数据,它必须是:

相同的协议和主机

您需要实现JSONP来解决它。

JSONP是一个不错的选择,但是还有一种更简单的方法。您可以简单地在服务器上设置Access-Control-Allow-Origin标头。将其设置为*将接受来自任何域的跨域AJAX请求。(https://developer.mozilla.org/en/http_access_control)

当然,这样做的方法因语言而异。下面是Rails版本:

class HelloController < ApplicationController
  def say_hello
    headers['Access-Control-Allow-Origin'] = "*"
    render text: "hello!"
  end
end

在本例中,say_hello动作将接受来自任何域的AJAX请求,并返回“hello!”响应。

下面是它可能返回的头的一个例子:

HTTP/1.1 200 OK 
Access-Control-Allow-Origin: *
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: text/html; charset=utf-8
X-Ua-Compatible: IE=Edge
Etag: "c4ca4238a0b923820dcc509a6f75849b"
X-Runtime: 0.913606
Content-Length: 6
Server: WEBrick/1.3.1 (Ruby/1.9.2/2011-07-09)
Date: Thu, 01 Mar 2012 20:44:28 GMT
Connection: Keep-Alive

尽管它很简单,但它确实有一些浏览器限制。看到http://caniuse.com/壮举=歌珥。

Jquery文档(链接):

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

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

它的工作,所有你需要:

PHP:

header('Access-Control-Allow-Origin: http://www.example.com');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

JS (jQuery ajax):

var getWBody = $.ajax({ cache: false,
        url: URL,
        dataType : 'json',
        type: 'GET',
        xhrFields: { withCredentials: true }
});