Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

javascript - Cross Domain Ajax Request with JQuery/PHP

Help, if you can-

The situation:

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

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

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

No luck.

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

Also no luck.

On the php side I have tried both the following:

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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).

Caveats:

  • 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").

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...