XMLHttpRequest javascript 原型不工作
XMLHttpRequest javascript prototypes not working
我们正在尝试通过 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 文件调用函数才会停止执行。从浏览器控制台手动调用函数会抛出
未捕获的引用错误:启动未定义
在 :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;
[...]
eval
在本地范围内工作,所以你的
eval(xhr.responseText);
...运行代码,就好像它在该回调中一样。顶级函数声明等不会是全局的。
如果你想在全局范围内评估代码,你可以使用 "indirect eval
" 技巧:
(0, eval)(xhr.responseText);
但是,我强烈建议退后一步,重新评估您正在做的事情。使用 XHR 请求脚本代码然后 eval
似乎关闭了。您可以改为将 script
元素附加到页面。
我们正在尝试通过 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 文件调用函数才会停止执行。从浏览器控制台手动调用函数会抛出
未捕获的引用错误:启动未定义
在 :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;
[...]
eval
在本地范围内工作,所以你的
eval(xhr.responseText);
...运行代码,就好像它在该回调中一样。顶级函数声明等不会是全局的。
如果你想在全局范围内评估代码,你可以使用 "indirect eval
" 技巧:
(0, eval)(xhr.responseText);
但是,我强烈建议退后一步,重新评估您正在做的事情。使用 XHR 请求脚本代码然后 eval
似乎关闭了。您可以改为将 script
元素附加到页面。