简体   繁体   中英

jQuery JSONP not calling the callback

I am having some 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 reality it will be returning some HTML code instead of the abcd .

Problem: abcd is not logged in console through myCallback . So what am i doing wrong ? I was under the impression that the data returned will be executed as it is inside script tags ?

If you use your own function, then you have to explicitly declare it as global . For example:

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

DEMO


Explanation

Every function that should be called in response to a successful JSONP request must be global. jQuery is doing this as well. This is because JSONP is nothing else than including a (dynamically generated (most of the time)) JavaScript file with a <script> tag, which only contains a function call. Since each script is evaluated in global scope, the function that is called must be global as well.

1) move the single quote from the called method (as Umesh Aawte wrote)

2) make the callback global

3) your callback is a part of jQuery now so this is your way to get your datas

hereafter the solution: (using jQuery : v3.3.1, node : v6.10.0, express : v4.16.3

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

$.ajax({
  url: my_url,
  type: 'GET',
  dataType: 'jsonp',
  jsonp: 'myCallback',
  jsonpCallback: myCallback
});

that's all folks!

Remove 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 this fiddle

Why not simply:

$.getJSON(my_url, myCallback);

this will handle function scoping and looks much simpler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM