I'm new to JavaScript and have run into an issue in calling the XMLHttpRequest function.
My code is as follows:
document.addEventListener('load', loadJsonFile(), false);
function reqListener() {
var obj = JSON.parse(this.responseText)
//Send for the html of a generic post
var reqObj = new XMLHttpRequest();
reqObj.onload = buildProjects(reqObj, obj);
reqObj.open("get", "post_box.html", true);
reqObj.send();
}
function buildProjects(reqObj, data){
for(var i = 0; i < 5; i++){
html = reqObj.responseText;
console.log("data is: " + data.title);
console.log("State: " + this.readyState);
console.log("Request object is: " + reqObj);
console.log("Response is: " + reqObj.response);
console.log("html is: " + html);
}
}
//Load all project data
//Then call reqListener function
function loadJsonFile(){
var reqObj = new XMLHttpRequest();
reqObj.onload = reqListener;
reqObj.open("get", "test.json", true);
reqObj.send();
}
I expected calling 'this' in the buildProjects() function would return the calling XMLHttpRequest object. This does not happen. Instead a 'Window' object is returned.
I tried working around this by passing the reqObj as parameters but this doesn't work either. I'm guessing this is a scope issue ?
I don't have any idea why the call to 'this' doesn't work. Calling 'this' works for me when I have a single XMLHttpRequest.onload function called, so I'm led to thinking it's something to do with nesting a request within a request ?
I've seen a similar question asked regarding functions called using arrow notation but I can't see how the answer there answers my problem.
Help is appreciated,
Thanks
UPDATE:
I managed to fix my issue by tagging .bind() to the end of a function call. This forces the keyword 'this' to be whatever value is passed in the bind() parameters. Thanks for the comments to point this out.
While my problem is fixed in this case, I still don't understand what went wrong originally. As I say, I'm fairly new to JS - a more detailed explanation would be appreciated !
Thanks again