简体   繁体   中英

JSONP only working with named callback function

I have gotten JSONP working with an anonymous function but can't get it to work with a named function. This code works (the alert appears with the correct data):

$.getJSON('http://example.com/test.aspx?foo=bar&callback=?',
    function (data) { alert(data.baz) })

However this code does not work (no alert appears):

function dat(data) {
     alert(data.baz)   
}

$.getJSON('http://example.com/test.aspx?foo=bar&callback=dat')

Can you explain why the last code does not work?

EDIT: I took out a non-relevant example

I'm not sure that leaving out the callback is the correct usage (or, at least, I cannot find any documentation that defines what should happen if a callback is not supplied). If you want to use a named function as the callback you can do:

function dat(data) {
    alert(data.baz)   
}

$.getJSON('http://example.com/test.aspx?foo=bar&callback=?', dat);

您应该能够通过类似以下方式遇到jQuery:

$.getJSON('http://example.com/test.aspx?foo=bar&callback=?', dat);

After looking at jquery's ajax code a bit, I think what you want to do is either do like Dave Ward and Hamish suggest, ie pass in the function. Or, I think you can pass the function's name as a string like this, since it is attached to the window and jquery looks at the type of the callback for determining behavior .

function dat(data) {
    alert(data.baz)   
}

$.getJSON('http://example.com/test.aspx?foo=bar&callback=?', 'dat');

Or, you can use getScript which will add the url as a script tag, which is fine for what you are trying to do.

function dat(data) {
    alert(data.baz)   
}

$.getScript('http://example.com/test.aspx?foo=bar&callback=dat');

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