Uncaught ReferenceError: foobar not defined (anonymous function)

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 () { } }) } }); 

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> 

When I hit this url: it says

 Uncaught ReferenceError:foobar is not defined (anonymous function) 

How to access the function from other domains?

+4
javascript jquery ajax
Dec 19 '11 at 10:19
source share
2 answers

You defined "foobar ()" inside the "ready" handler. Therefore, it is a local variable in this function and invisible outside of it.

You can add this to the end of the "ready" handler:

  window['foobar'] = foobar; 

and then it will be displayed globally.

By the way, this is something that can be bitten in jsfiddle , because it (by default) will wrap the code in the load handler.Thus , if you copy / paste from a JavaScript file included in <head> , a function that would be global in this context, ends not global in the script.

+11
Dec 19 '11 at 10:21
source share

Your function is not visible globally, as indicated in Pointy. But you also load the script and call the function defined by the ready() function. I think it is possible that ready() can be called when your script calls foobar() , which will generate the same error. I would recommend that you set the global value in the script, and then use this variable in the ready() function.

Set the value in the script:

 <script src='http://foobar.com/static/js/main.js' type='text/javascript'></script> <script type='text/javascript'>var bar = '123456'</script> 

Then you can use it in the ready() function.

 $(document).ready(function() { $.ajax({ url: "/site/foo/", data: {'foo':bar}, dataType: "jsonp", crossdomain: !0, success: function (data) { alert(data); }, error: function () { } }); }); 

If you want to define a function so that it can be used again, you can call it in ready() , but make sure that you set the global variable bar to what you want.

 window.foobar = function() { $.ajax({ url: "/site/foo/", data: {'foo':bar}, dataType: "jsonp", crossdomain: !0, success: function (data) { alert(data); }, error: function () { } }); } $(document).ready(function() { foobar(); // other stuff }); 
0
Dec 19 '11 at 10:48
source share



All Articles