首页 > 解决方案 > XMLHttpRequest javascript原型不起作用

问题描述

我们正在尝试通过 w3-include-html 函数将我们的网站包含在另一个网站上,然后是一些用于 *.js 文件的 xmlhttprequests。

function loadJS(url,onDone,onError){
var xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange=function(){
    if(xhr.readyState==4){
        if(xhr.status==200||xhr.status==0){
            setTimeout(function(){
                try{
                    eval(xhr.responseText);
                }catch(e){
                }
                onDone();
            }.bind(this),1);
        }else{
        }
    }
}.bind(this);
try{
    xhr.open("GET",url,true);
    xhr.send();
}catch(e){
}};

这似乎可行,仅从另一个 .js 文件调用函数会停止执行。从浏览器控制台手动调用函数会抛出
Uncaught ReferenceError: splash is not defined at :1:1
这只发生在也是原型的函数中。

第一个 .js 文件:

var eless = function () {
this.$body = $('body');
var self = this;
window.dataLayer = window.dataLayer || [];

this.init();
this.loop();
console.log("before");
new splash();
console.log("after");

第二个 .js 文件:

var splash = function() {
console.log('after after');
console.log(this.init);
this.init();
console.log("after after after");
};
splash.prototype = {
init: function () {
    var self = this;
[...]

标签: javascriptxmlhttprequestprototype

解决方案


eval在本地范围内工作,所以你的

eval(xhr.responseText);

...运行代码,就好像它在该回调中一样。顶级函数声明等不会是全局的。

如果要在全局范围内评估代码,可以使用“间接eval”技巧:

(0, eval)(xhr.responseText);

但是,我强烈建议您退后一步,重新评估您正在做的事情。使用 XHR 来请求脚本代码,你eval似乎就不行了。您可以script改为将元素附加到页面。


推荐阅读