3

Simple question, if I have static file like this one(generated JSON using mockJSON web)

http://www.webwrx.sk/clients/data.json.txt

What I need to do with this file to change it to JSONP? Do I need to modify it somehow? How is it different to file like api.flickr.com ?

http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any%20&format=json&jsoncallback=?

I have even added () into that file:

http://www.webwrx.sk/clients/data2.json.txt

Still following code wont work:

    var params = _.extend({
        'method': 'GET',
        'url': this.url,
        'cache': true,
        'dataType': 'jsonp',
        processData: true
    }, options);

    return $.ajax(params);

Thank you for any help.

feronovak
  • 2,687
  • 6
  • 35
  • 54

1 Answers1

5

The only difference between JSON and JSONP format is the presence of the function call in the latter.

JSON:

[ "foo", "bar" ]

JSONP:

callback([ "foo", "bar" ])

Make sure you have a function of that name (here: callback) defined in your code, as it will be invoked:

function callback(jsondata) {
  console.log("I got this:", jsondata)
}

jQuery abstracts the callback naming thing, so you can simply have "jsoncallback=?" in URI (assuming the server is flexible enough to know to name the function according to a parameter), and pass an anonymous function into the jQuery call. jQuery will assign the function to an autogenerated random name, then replace the question mark in your URI with that name. However, you can't do that if you're reading a static file (it will have a fixed function name, so it can't change it dynamically to the autogenerated name jQuery passes it). Here is a working example with jQuery (not mine).

Community
  • 1
  • 1
Amadan
  • 191,408
  • 23
  • 240
  • 301