且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

getScript加入本地负载不是全局的?

更新时间:2023-12-04 23:08:10

我相信我已经找到使用普通的JQuery的AJAX调用的解决方案。关键就在于,设置数据类型为文本,否则,如果它的脚本,或者使用getScript加入或替代方案。获得(),它会自动运行脚本中,并将其在全球范围内。

 函数ABC(){
    VAR味精=侨;
    $阿贾克斯({
      网址:'主题/ _default /系统/ message.js',
      成功:功能(数据){
          的eval(数据);
      },
      数据类型:文字
    });
    }
    //message.js
(功能() {
    警报(味精);
})();
 

此提示侨预期:)

在任何人说任何事是我使用的eval,但其完全没有这种情况。

From what I have read JQuery's getScript function loads the script file in a global context using a function called 'global eval'. Is there a particular setting or method to change this so it will instead load within the function I am calling it from?

If I do the following code name returns undefined as its not loading the script in the local context.

    function callscript(){
        var name='fred';
    getScript(abc.js);
    }

//abc.js:
alert(name);

I believe I have found the solution using a regular JQuery ajax call. The trick is you set the datatype to 'text' as otherwise if its script or if use getScript or the alternative .get() it will auto run the script inside and place it in the global context.

 function abc(){
    var msg="ciao";
    $.ajax({
      url: 'themes/_default/system/message.js',
      success: function(data){
          eval(data);
      },
      dataType: "text"
    });
    }
    //message.js
(function() {
    alert(msg);
})();

This alerts 'ciao' as expected :)

Before anyone says anything yes I'm using eval but its perfectly fine in this situation.