跨域Ajax请求使用jQuery / PHP [英] Cross Domain Ajax Request with JQuery/PHP

查看:111
本文介绍了跨域Ajax请求使用jQuery / PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

帮助,如果可以的话 -

Help, if you can-

情况:

http://foobar.com 包括远程托管javacript文件(http://boobar.com/stuff。 JS)。

http://foobar.com includes a remotely hosted javacript file (http://boobar.com/stuff.js).

我们的目标是刚刚获得来自远程托管的PHP脚本警报在foobar.com

The goal is to just get an alert from the remotely hosted php script on foobar.com

我曾尝试以下code在stuff.js:

I have tried the following code in stuff.js:

$.ajax({
  type: "GET",
  url: "http://www.boobar.com/script.php?callback=?",
  dataType: 'jsonp',
  success: function(result) { alert(result); }
});

没有运气。

$.getJSON("http://www.boobar.com/script.php?jsonp=?",
  function(data) { alert(data); }
);

也没有运气。

Also no luck.

在PHP端我曾尝试以下两个:

On the php side I have tried both the following:

return json_encode(array(0 => 'test'));

echo json_encode(array(0 => 'test'));

在Firefox中,我收到了安全性错误。我明白,它认为我违反了安全模型。然而,根据本jquery的文档,我应该能够做到这一点。

In Firefox I get a security error. I understand that it thinks I'm violating the security model. However, according to the jquery documentation, I should be able to accomplish this.

推荐答案

该错误似乎是的同源策略:简化,你只能让AJAX源服务器上的请求的东西( http://foobar.com )。解决此一方法是使原始服务器上的简单的外观,例如:

The error seems to be a security feature of the Same Origin Policy: to simplify, you can only make AJAX requests for stuff on the originating server (http://foobar.com). One way around this is to make a simple facade on the originating server, e.g.:

 <?php
 // this file resides at http://foobar.com/getstuff.php
 echo file_get_contents('http://www.boobar.com/script.php?callback=?'
          . $possibly_some_other_GET_parameters );
 ?>

然后,从foobar.com,可以使一个AJAX请求 http://foobar.com/getstuff.php (这反过来又使一个HTTP GET请求从你的web服务器 boobar.com ,并将其发送回浏览器)。

Then, from foobar.com, you can make an AJAX request for http://foobar.com/getstuff.php (which in turn makes a HTTP GET request from your web server to boobar.com and sends it back to the browser).

要在浏览器中,请求进入到源服务器,并允许(在浏览器有没有办法知道,响应来自其他地方的幕后的)。

To the browser, the request goes to the origin server, and is allowed (the browser has no way of knowing that the response comes from somewhere else behind the scene).

注意事项:

  • 的PHP配置在foobar.com必须具有 allow_url_fopen选项设置为1。虽然这是默认设置,有些服务器有禁用它。
  • 请求www.boobar.com从foobar.com 服务器制成,而不是浏览器。这意味着没有cookie或用户身份验证的数据将被发送到www.boobar.com,只是无论你投入的请求URL( $ possibly_some_other_GET_parameters )。
  • the PHP config at foobar.com must have allow_url_fopen set to "1". Although this is the default setting, some servers have it disabled.
  • the request to www.boobar.com is made from foobar.com server, not from the browser. That means no cookies or user authentication data are sent to www.boobar.com, just whatever you put into the request URL ("$possibly_some_other_GET_parameters").

这篇关于跨域Ajax请求使用jQuery / PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆