2010-10-27 16:52
浏览 58

同源策略 - JavaScript调用PHP

I know that this is a popular topic, but I've yet to find an answer that's completely comprehensive.

I'm trying to create a simple way for our 'customers' to place a Google Map on their website, which plots the position of our customers (or a subset thereof) on the map. The customers are in a MySQL database which is turned into XML on-the-fly by a PHP script (as per Google's example). This works fine on my website, but when I try it on another website the xmlHTTPRequest is not allowed to look at the PHP as it's on another domain.

I can circumvent this by writing another PHP file on the other domain which simply reads the PHP file on the original domain. But not all our customers will have PHP running on their servers. Is there any way that I can return the XML results from our database using JavaScript?

A couple of points:

  1. The JavaScript that makes the xmlHTTPRequest still sits on our server -- our clients link to it from a script tag. I thought that might be enough, but the 'origin' (according to Chrome, anyway) is still seen as domain#2

  2. This is great: if I use an absolute reference in the xmlHTTPRequest (e.g.'GET', '', true)) then it will fail in IE, but if I use a relative reference ('/api/foo.php') it will work.

  3. I don't know enough about it, but could I use JSON? I've seen: 'script src="http://..../someData.js?callback=some_func"' but don't know how, I would make 'someData.js' look like JSON? (I'm thinking very much in terms of functions, which probably is incorrect?).

  4. I've tried adding: header("Access-Control-Allow-Origin: *"); to the top of the PHP that outputs the XML, but it's not really doing much that I can tell!

  5. If I do use a PHP wrapper on the client's server, what's the advantage of using a cURL request, rather that simple file_get_contents or fopen?

Sorry, lots of questions, but any guidance would be greatly appreciated.

Massive thanks,


图片转代码服务由CSDN问答提供 功能建议


我正在尝试为我们的“客户”创建一种简单的方法,在他们的网站上放置Google地图,在地图上绘制客户(或其子集)的位置。 客户在MySQL数据库中,通过PHP脚本(根据Google的示例)即时转换为XML。 这在我的网站上工作正常,但是当我在另一个网站上尝试时,xmlHTTPRequest不允许查看PHP,因为它在另一个域上。

我可以通过编写另一个PHP来避免这种情况 另一个域上的文件只读取原始域上的PHP文件。 但并非所有客户都会在其服务器上运行PHP。 有什么方法可以使用JavaScript从我们的数据库返回XML结果吗?


  1. < p>使xmlHTTPRequest的JavaScript仍然位于我们的服务器上 - 我们的客户端从脚本标记链接到它。 我认为这可能已经足够了,但“起源”(根据Chrome,无论如何)仍然被视为域#2
  2. 这很棒:如果我使用的话 xmlHTTPRequest中的绝对引用(例如'GET','',true))然后它将在IE中失败,但如果我使用相对引用(' /api/foo.php')它会起作用。

  3. 我对此知之甚少,但我可以使用JSON吗? 我见过: script src =“http://..../someData.js?callback = some_func”' 但是我不知道如何,我会让'someData.js'看起来像JSON? (我在功能方面非常考虑,可能不正确?)。

  4. 我尝试添加: header(“Access-Control-Allow” -Origin:*“); 输出XML的PHP​​的顶部,但它并没有真正做到我能说的很多!

  5. 如果我使用的话 客户端服务器上的PHP包装器,使用cURL请求有什么好处,而不是简单的file_get_contents或fopen?

    抱歉,很多问题 ,但任何指导都将不胜感激。



  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题