javascript - 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;
[...]
解决方案
eval
在本地范围内工作,所以你的
eval(xhr.responseText);
...运行代码,就好像它在该回调中一样。顶级函数声明等不会是全局的。
如果要在全局范围内评估代码,可以使用“间接eval
”技巧:
(0, eval)(xhr.responseText);
但是,我强烈建议您退后一步,重新评估您正在做的事情。使用 XHR 来请求脚本代码,你eval
似乎就不行了。您可以script
改为将元素附加到页面。
推荐阅读
- maven - Websphere 9 Maven 远程部署
- sql - 如何终止在 SQL Server 中执行时间过长的请求
- django - 有没有办法在同一个项目中运行 React + Django 而无需一次又一次地运行 npm run build ?
- java - 在 Storm 2.1.0 中找不到 ResourceAwareScheduler
- c# - Json转换复杂字典
- java - androidstudio java错误导致应用程序崩溃
- postgresql - 如何在 postgres 中访问上次升级日期和版本
- google-colaboratory - AttributeError:模块“tensorflow._api.v1.compat.v1”没有属性“contrib”
- reactjs - 无法在 reactJS Typescript 中获取输入值
- linux - iTop Combodo 中的 OCS 库存集成