[英]Use external JS to import data from XML
I have very much javascript code in my HTML file (1500 lines), and I want to move parts of it to an other js file. 我的HTML文件中有很多javascript代码(1500行),我想将其中的一部分移到另一个js文件中。 I want to make a single file for importing data, and I can find the best way to do it. 我想制作一个用于导入数据的文件,并且可以找到最佳的方法。
This is my gameDataImport.js file: 这是我的gameDataImport.js文件:
function gameImport(gameID){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","../riskmanagment/Data/gameData.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var numberOfWorkers;
var x=xmlDoc.getElementsByTagName("game");
for (i=0;i<x.length;i++)
{
if(x[i].getAttribute('id') == gameID)
{
this.gameName = x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
this.numberOfWorkers = x[i].getElementsByTagName("numberOfWorkers")[0].childNodes[0].nodeValue;
this.numberOfWorkersLeft = numberOfWorkers;
this.overtimeWorkers = x[i].getElementsByTagName("overtimeWorkers")[0].childNodes[0].nodeValue;
this.overtimeWorkersLeft = overtimeWorkers;
this.difficulty = x[i].getElementsByTagName("difficulty")[0].childNodes[0].nodeValue;
this.budget = x[i].getElementsByTagName("budget")[0].childNodes[0].nodeValue;
this.gameTargetMinutes = x[i].getElementsByTagName("targetGameTime")[0].childNodes[0].nodeValue;
this.gameTargetDays = x[i].getElementsByTagName("targetDays")[0].childNodes[0].nodeValue;
this.gameLanguage = x[i].getElementsByTagName("language")[0].childNodes[0].nodeValue;
this.projectDescriptionText = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
this.wage = x[i].getElementsByTagName("wage")[0].childNodes[0].nodeValue;
this.Owage = x[i].getElementsByTagName("Owage")[0].childNodes[0].nodeValue;
this.numberOfRisks = x[i].getElementsByTagName("numberOfRisks")[0].childNodes[0].nodeValue;
}
}
And this how I try to get the data: 这就是我尝试获取数据的方式:
in head: 在头上:
<script type="text/javascript" src="js/gameDataImport.js"></script>
in body, inside script tag: 在正文中,在脚本标签内:
numberOfWorkers = gameImport(gameID).numberOfWorkers;
but I only get this error: 但是我只得到这个错误:
Uncaught TypeError: Cannot read property 'numberOfWorkers' of undefined 未捕获的TypeError:无法读取未定义的属性'numberOfWorkers'
I have not tried more than one variable, but will try that one first. 我没有尝试多个变量,但是将首先尝试该变量。
您忘记了GameImport函数的右花括号
我不知道这是否有帮助,但是我解决了删除脚本的type属性的问题,如下所示:
<script src="js/gameDataImport.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.