0

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

3
  • Are you sure the last one does not work? It is actually the same as the first one. Commented Feb 3, 2011 at 19:33
  • @Felix, you're right... I tried that example again and now it works, so I took it out of the question... but there is still the remaining one that does not work (which I also tested again to be sure) Commented Feb 3, 2011 at 19:39
  • @BaroqueBobcat, it's right before the getJSON call, which is in <body><form><div><script> Commented Feb 3, 2011 at 19:46

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

You should be able to meet jQuery half way with something like this:

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

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.