Search code examples
javascriptxmlexternal-js

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. 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:

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

I have not tried more than one variable, but will try that one first.


Solution

  • I don't know if this could help, but I solved this issue removing type attribute of the script, like this:

    <script src="js/gameDataImport.js"></script>