PHP,jQuery Ajax和json通过跨域返回 [英] PHP, jQuery Ajax and json return over a cross domain
问题描述
我在一台服务器上有我的php编码页面,该页面返回json结果. php文件名为:getInfoData.php,返回结果如下.
I have my php coded page on one server that returns a json result. php file called: getInfoData.php and the return is as below.
echo json_encode($v);
不,我可以使用$ .getJSON(??)来读取json并以相同的服务器名运行它,但是我需要将php页面的服务器名与调用它的js页面的服务器名不同.
No I can use $.getJSON(??) to read the json and run it all on the same sever fine, but I need the php page to be on a different sever than the js page calling it.
但是后来我得到跨域问题.
But then I get then when I do I get the cross domain issue.
所以我将代码更改为使用以下(jsonp):
So I changed the code to use the following (jsonp):
$.ajax({
url: 'FILE_LOCATION_ON_ANOTHER_SERVER',
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function() { console.log("Success"); },
error: function() {console.log('Failed!'); }
});
但是我什么都看不到,我只能通过控制台获得以下信息:
but I do not see anything I just get the following with my console:
http://www.THEURL.com/FOLDER/FILENAME.php?callback=jQuery171013088115444406867_1332256223342&_=1332256223343
和一条消息说失败了!.
and a message saying failed!.
我在做什么错,怎么办才能解决?
What am I doing wrong and how if at all can I fix this?
谢谢
推荐答案
JSONP实际上不是JSON.这有点黑客". JSONP实际上是一个JavaScript文件,可以下载并运行.
JSONP isn't actually JSON. It's a bit of a "hack". JSONP is actually a JavaScript file, that gets downloaded and ran.
在您的PHP页面中,应该为您传递一个callback
参数.您需要在其中包装" JSON.它应该看起来像这样:
In your PHP page, you should be passed a callback
parameter. You need to "wrap" your JSON in it. It should look like this:
func({json: data})
因此,您的PHP应该如下所示:
So, your PHP should look like this:
echo $_GET['callback'] . '(' . json_encode($v) . ')';
这篇关于PHP,jQuery Ajax和json通过跨域返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!