简体   繁体   中英

PHP script returns error/nothing when fetching data with AJAX

I have a PHP file called 'myProxy.php' sitting on my server that looks like this:

<?php
 echo "text";
 exit();
?>

When I try to get that string from the file with an AJAX call that looks like this:

$.ajax({
    url: "http://www.mydomain.com/myProxy.php",
    type: "GET",
    success: function(data) {
     alert("Horray!");
  }
 });

The script turns absolutely nothing and I get a red error icon in the Firebug console. Does anyone know what might be causing this? Perhaps a setting is not set somewhere?

Same origin policy .

You can't place your script on another domain/subdomain/protocol than your current script is

I have a feeling you're running into a same origin policy restriction.

For plain old AJAX, your script and resource should exist on the same domain. If this is actually the case, you can simply use

$.get("/myProxy.php", function(data) {
    alert("Hooray!");
}, "text");

If you truly need cross-domain support, you can change your PHP script to respond to JSONP requests

<?php
// myProxy.php
$callback = isset($_GET['callback']) ? $_GET['callback'] : 'callback';
$data = array('text' => 'text');
header('Content-type: text/javascript');
printf('%s(%s)', $callback, json_encode($data));

... and the JavaScript

$.getJSON("http://www.domain.com/myProxy.php?callback=?", function(data) {
    alert(data.text);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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