简体   繁体   English

jQuery getJSON到外部PHP页面

[英]jQuery getJSON to external PHP page

I've been trying to make an AJAX request to an external server. 我一直在尝试向外部服务器发出AJAX请求。 I've learned so far that I need to use getJSON to do this because of security reasons ? 到目前为止,我已经了解到,由于安全原因,我需要使用getJSON来执行此操作?

Now, I can't seem to make a simple call to an external page. 现在,我似乎无法对外部页面进行简单的调用。 I've tried to simplify it down as much as I can but it's still not working. 我试图尽可能地简化它,但它仍然无法正常工作。 I have 2 files, test.html & test.php 我有2个文件,test.html和test.php

my test.html makes a call like this, to localhost for testing : 我的test.html这样打电话给localhost进行测试:

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

and I want my test.php to return a simple 'test' : 我希望我的test.php返回一个简单的'测试':

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

I'm probably making some incredible rookie mistake but I can't seem to figure it out. 我可能会犯一些令人难以置信的菜鸟错误,但我似乎无法弄明白。 Also, if this works, how can I send data to my test.php page, like you would do like test.php?id=15 ? 此外,如果这有效,我怎样才能将数据发送到我的test.php页面,就像test.php?id = 15一样?


The test.html page is calling the test.php page on localhost, same directory I don't get any errors, just no alert .. test.html页面调用localhost上的test.php页面,同一目录我没有收到任何错误,只是没有警告..

It could be that you haven't got a callback in test.php. 可能是你在test.php中没有回调。 Also, json_encode only accepts an array: 此外, 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

jQuery automatically switches to JSONP (ie using script tags instead of XMLHttpRequest ) when you use http:// . 当您使用http://时,jQuery会自动切换到JSONP(即使用脚本标记而不是XMLHttpRequest )。 If you have test.html and test.php on the same domain, try using relative paths (and no callbacks). 如果在同一个域上有test.html和test.php,请尝试使用相对路径(并且不使用回调)。

Be careful with moff's answer. 小心moff的回答。 It's got a common XSS vulnerability: http://www.metaltoad.com/blog/using-jsonp-safely 它有一个常见的XSS漏洞: http//www.metaltoad.com/blog/using-jsonp-safely

The simplest solution would be to add the below code before any output to your test.php file, then you have more flexibility with what methods you use, a standard ajax call should work. 最简单的解决方案是在test.php文件的任何输出之前添加以下代码,然后您可以更灵活地使用您使用的方法,标准的ajax调用应该起作用。

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

However, use the json callback thing when your getting data from a server beyond your control. 但是,当您从服务器获取的数据超出您的控制范围时,请使用json回调函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM