[英]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. 我已经使JSONP使用匿名函数,但无法使其与命名函数一起使用。 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. 在看了一下jquery的ajax代码后,我认为您想要做的就是像Dave Ward和Hamish建议的那样,即传递函数。 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 .
或者,我认为您可以将函数名称作为这样的字符串传递,因为它附加在窗口上,并且jquery会查看用于确定行为的回调的类型 。
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. 或者,您可以使用getScript将该URL添加为脚本标记,这对您尝试执行的操作很合适。
function dat(data) {
alert(data.baz)
}
$.getScript('http://example.com/test.aspx?foo=bar&callback=dat');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.