Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify the callback parameter with JQuery.getJSON

Tags:

json

jquery

jsonp

Is there any way to specify the value of the callback parameter when using JQuery's getJSON method?

For example:

$.getJSON('/content?callback=?', function(data) {});

Generates the following URL:

content?callback=jQuery15108431726952168015_1299633045933&_=1299633046552

The parameter here is generated randomly by the library.

I would like to specify my own callback parameter.

I would like to use the same callback parameter for every request so I can aggresively cache the response.

like image 498
Toby Hede Avatar asked Dec 06 '25 13:12

Toby Hede


2 Answers

You need to be at least on jQuery 1.5 for this to work.

// The URL generated is "/content?callback=myCallback"
$.ajax({
  url: '/content?callback=?',
  dataType: 'jsonp',
  jsonpCallback: 'myCallback',
  cache: true,
  success: function(data) {}
});
like image 172
htanata Avatar answered Dec 08 '25 05:12

htanata


All of jQuery's ajax convenience functions are just wrappers for $.ajax.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

Why not create your own convenience wrapper?

function fetchJSON(url, data, callback) {
    return jQuery.get(url, data, callback, "json");
}
like image 21
makfak Avatar answered Dec 08 '25 03:12

makfak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!