How can I get data from an external URL in jQuery?
Consider:
var resturl = "http://example.com";
cj.getJSON(
resturl + "&callback=?",
function(data)
{
console.log(data);
}
);
My callback function i开发者_JS百科s never called. Why?
Two things here:
First, your URL addition should be "?callback=?"
since there's no other querystring, or use the full $.ajax()
call with a jsonp
data type, so it adds the querystring as needed, like this:
$.ajax({
url: resturl,
dataType: 'jsonp',
success: function(data){
console.log( data );
}
});
Second, the domain you're going to has to support JSONP.
Remember that jQuery is going to execute your callback as a function, so you've got to make sure that the JSON returned by your server is wrapped as a callback.
Here's a very simple working example.
JavaScript:
var myURL = "http://www.someserver.com/somegreatapplication.php?callback=?";
$.getJSON(myURL, function(data) {
$("#somediv").html(data.htmlCode);
});
File somegreatapplication.php
<?php
$output['htmlCode'] = "<b>This worked!</b>";
// Properly format the JSONP response //
$json = json_encode( $output);
header("Content-type: application/json");
exit( $_GET['callback'] . ' (' . $json . ');' );
?>
Notice that the PHP code will not return raw JSON code like you're probably used to, but it will actually return the callback function, including the JSON. jQuery will turn your URL into something like this:
http://www.someserver.com/somegreatapplication.php?callback=jsonp1283446768493&_=1283446768526
Your PHP code would then output this:
jsonp1283446768493({"menuHTML":"<b>This worked!</b>"});
That gets run, and then the object is available within your getJSON( ... function(){} );
All of this of course assumes that you're controlling both ends of the communication. If you don't, then you need to make sure that the other end is giving you proper JSONP output (you may need to use a specifically named callback if they are forcing that).
This should work as long as the server side sends the data and uses JSONP
var resturl = "http://example.com";
$.getJSON(resturl,{"callback":"?"},function(data, textStatus){ console.log(data)});
According to the documentation the callback is only executed on success. So the request in general might have failed. The URL that is constructed also doesn't really contain a valid query string. You start the query string with a ?
, but your URL just contains a &
which indicates additional query string parameters:
callback(data, textStatus)A callback function that is executed if the request succeeds.
http://api.jquery.com/jQuery.getJSON/
But I'm not sure if the additional JSONP option changes something about this policy.
精彩评论