如何将数据传递到加载$ .getScript()的外部脚本?

wyq*_*syq 5 javascript ajax jquery

所以我试图使用jquery的$ .getScript远程加载一个javascript,但我很困惑我如何将数据传递给外部脚本.

我已经尝试在调用之前设置变量,但它们在加载的脚本中不可用,当我尝试使用查询字符串发送/检索它们时,远程脚本尝试读取它的基本文件的查询字符串从而不是自己被召唤.有没有其他方法可以做到这一点?或者是否有可能让javascript文件读取自己的查询字符串而不是从中调用的文件(在浏览器中加载)?

// editor ini
var editor_ini = { page: current_page, action: 'edit' };
var foo = 'bar';
// load the editor
$.getScript('assets/desktop/desklets/'+launcher.config.editor+'/execute.js', function(){});
Run Code Online (Sandbox Code Playgroud)

在execute.js文件中,editor_inifoo都不可用,我得到相同的结果:

// load the editor
$.getScript('assets/desktop/desklets/'+launcher.config.editor+'/execute.js', { page: current_page, action: 'edit', foo: 'bar' }, function(){});
Run Code Online (Sandbox Code Playgroud)

因为远程脚本似乎从原始文档获取查询字符串而不是调用文件时使用的查询字符串.

如果重要,我试图使用jquery 的查询对象插件来读取查询字符串.

Bha*_*nan 6

在内联javascript中声明的全局变量可以在加载的外部javascript页面中访问.$.getScript().确保变量是全局的


Ale*_*kov 5

我敢打赌你的var foo='bar'在函数内部,所以在全局范围内不可见.尝试:

window.foo = 'bar'
Run Code Online (Sandbox Code Playgroud)