JQuery JSONP does not call a callback

I am having a problem with jsonp and jquery.

This is my code -

var myCallback = function(data) { console.log(data); }; $.ajax({ url: my_url, type: 'GET', dataType: 'jsonp', jsonp: 'callback', jsonpCallback: 'myCallback' }); 

jQuery adds something like ?callback=myCallback&_=1340513330866 to my_url, and the data returned from my_url is myCallback('abcd') - although in fact it will return some HTML code instead of abcd .

Problem: abcd does not enter the console through myCallback . So what am I doing wrong? I got the impression that the returned data will be executed, since it is inside the script tags?

+8
javascript jquery jsonp
source share
3 answers

If you use your own function, you need to explicitly declare it as globally . For example:

 window.myCallback = function(data) { console.log(data); }; 

Demo


Explanation

Each function that must be called in response to a successful JSONP request must be global. jQuery does this as well. This is because JSONP is nothing more than a (dynamically generated (most often)) JavaScript file with a <script> tag that contains only a function call. Because each script is evaluated in global scope, the function being called must also be global.

+16
source share

Why not just:

 $.getJSON(my_url, myCallback); 

it will handle functions and looks a lot easier

0
source share

Remove the single quote from the called method, this will work. Please check the code here,

 var myCallback = function(data) { console.log(data); }; $.ajax({ url: my_url, type: 'GET', dataType: 'jsonp', jsonp: 'callback', jsonpCallback: myCallback }); 

Try fiddle

-one
source share

All Articles