问题描述
我有这个js一些领域提供文件说 foobar.com
I have this js file serving from some domain say foobar.com
at http://foobar.com/static/js/main.js:
$(document).ready(function() {
function foobar(bar){
$.ajax({
url: "/site/foo/",
data: {'foo':bar},
dataType: "jsonp",
crossdomain: !0,
success: function (data) {
alert(data);
},
error: function () {
}
})
}
});
在 barfoo.com
上的一些URL,我有这样的事情:
On barfoo.com
on some url, I have something like this:
<script src='http://foobar.com/static/js/main.js' type='text/javascript'></script>
<script type='text/javascript'>foobar('123456')</script>
当我打的网址:它说
Uncaught ReferenceError:foobar is not defined (anonymous function)
如何从其他域访问功能?
How to access function from other domains?
推荐答案
您已经定义了foobar的()内的准备就绪的处理程序。因此它的外它在该函数中的局部变量,和不可见。
You've defined "foobar()" inside the "ready" handler. It's therefore a local variable in that function, and invisible outside it.
您可以把它添加到准备处理程序结束:
You could add this to the end of the "ready" handler:
window['foobar'] = foobar;
,然后它会在全球是可见的。
and then it'd be visible globally.
顺便说一句,这是东西可以咬的jsfiddle ,因为它(默认情况下),将包装的负荷code处理器。因此,如果你复制/从包含在JavaScript文件粘贴到&LT; HEAD&GT;
,一个功能,这将是全球在这方面最终没有全球性的小提琴
By the way this is something that can bite at jsfiddle because it (by default) will wrap code in a "load" handler. Thus, if you copy/paste from a JavaScript file included in the <head>
, a function that would be global in that context ends up not global in the fiddle.
这篇关于未捕获的ReferenceError:foobar的未定义(匿名函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!