Reputation: 6117
I'm trying to work with a JSONP API, across domains. This is an example of the data it returns:
photos({"marker":{"@attributes":{"id":"30601","latitude":"52.638061","longitude":"-2.117067","feature":"3","caption":"cat","thumbnailSizes":"60|120|150|180|200|250|300|350|400|400|425|450|500|640"}}});
How can I construct an Ajax call that makes use of this data? I keep getting error messages.
This is what I'm trying at the moment:
$.ajax({
url: pm_url,
data: {},
type: "get",
dataType: "jsonp",
cache: false,
success: function(data) {
console.log(data);
},
error: function() {
alert('Sorry, there was a problem getting the photos!');
}
In Firebug, I can see that the data above is being retrieved, but then I see the error message.
What is wrong with the request? (Or the data - though it validates as JSONP.)
UPDATE:
Thanks for the suggestions. I'm now trying:
var photos = function (data) {
alert(data);
};
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
});
This is, weirdly, calling two URLs in Firebug:
http://myapi.com/file.jsonp?x=1&y=2?callback=?
http://myapi.com/file.jsonp?x=1&y=2?callback=photos&_=1304982373561
The first URL is showing up as an error in the Console. What am I doing wrong?!
It's possible that the API itself is wrong (they're requiring a .jsonp suffix and ignoring the value of callback, which is why the function name is fixed) but I was hoping I could work around it.
Upvotes: 3
Views: 2583
Reputation: 117334
The function-name(photos) is wrong. jQuery will send a GET-parameter named "callback", the value of this parameter is the name the function needs to have.
Response, PHP-example:
<?php echo $_GET['callback'].'('.json_encode($some_object).');';?>
To explain what happens with jsonp:
assuming a callback-parameter send with value jquery1234: jQuery will create a temporary function:
function jquery1234(data){return data;}
So if you send a response like
jquery1234({'somevar':'somevalue'});
...jQuery will create a script-element of that response, the function gets called and the object will be transferred to the success-function.
Upvotes: 4