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


当前回答

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

其他回答

它的工作,所有你需要:

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

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

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/壮举=歌珥。

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

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

使用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用自己生成的回调方法替换它)。