9

我一直在尝试向外部服务器发出 AJAX 请求。到目前为止,我了解到出于安全原因我需要使用 getJSON 来执行此操作?

现在,我似乎无法简单地调用外部页面。我试图尽可能地简化它,但它仍然无法正常工作。我有 2 个文件,test.html 和 test.php

我的 test.html 像这样调用 localhost 进行测试:

    $.getJSON("http://localhost/OutVoice/services/test.php", function(json){
    alert("JSON Data: " + json);
});

我希望我的 test.php 返回一个简单的“测试”:

$results = "test";
echo json_encode($results);

我可能犯了一些令人难以置信的菜鸟错误,但我似乎无法弄清楚。另外,如果这可行,我怎样才能将数据发送到我的 test.php 页面,就像你会做的那样 test.php?id=15 ?


test.html 页面在本地主机上调用 test.php 页面,同一目录我没有收到任何错误,只是没有警报..

4

3 回答 3

17

可能是您在 test.php 中没有回调。此外,json_encode只接受一个数组:

$results = array("key" => "value");
echo $_GET['callback'] . '(' . json_encode($results) . ')';
// the callback stuff is only needed if you're requesting from different domains

XMLHttpRequest您使用http://. 如果您在同一个域上有 test.html 和 test.php,请尝试使用相对路径(并且没有回调)。

于 2009-04-26T14:26:44.877 回答
15

小心moff的回答。它有一个常见的 XSS 漏洞:http ://www.metaltoad.com/blog/using-jsonp-safely

于 2010-11-19T20:57:15.783 回答
2

最简单的解决方案是在 test.php 文件的任何输出之前添加以下代码,然后您可以更灵活地使用您使用的方法,标准 ajax 调用应该可以工作。

header ('Access-Control-Allow-Origin: *');

但是,当您从无法控制的服务器获取数据时,请使用 json 回调。

于 2012-04-06T20:45:16.337 回答