简体   繁体   English

如何在“脚本”数据类型AJAX请求之后访问声明的变量?

[英]How to access declared variables after a “script” data type AJAX request?

First off, thanks for your attention. 首先,感谢您的关注。

I have this variable declared at the top of my script: 我在脚本顶部声明了此变量:

var declaredVariable = 'test';

After, I have this AJAX call: 之后,我有这个AJAX呼叫:

$.ajax ({
    url: 'example-external.js',
    method: 'post',
    dataType: 'script'
});

The requests works. 这些请求有效。 The file example-external.js is correctly loaded. 文件example-external.js已正确加载。

However, inside the file example-external.js , I'd like to do this: 但是,在文件example-external.js中 ,我想这样做:

console.log(declaredVariable);

I just need to access a previously declared variable. 我只需要访问一个先前声明的变量。 But that doesn't work :( 但这不起作用:(

How do I access that variable inside my Javascript file? 如何在Javascript文件中访问该变量?

Thank you. 谢谢。


Solution! 解!

I've declared my variable as global: 我已将我的变量声明为全局变量:

window.declaredVariable = 'test';

Instead of: 代替:

var declaredVariable = 'test';

Thanks to techfoobar ! 感谢techfoobar

Use jQuery.getScript() instead 使用jQuery.getScript()代替

$.getScript( 'example-external.js', function( data, textStatus, jqxhr ) {
   //done
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM