Hi,
I have a few questions about the onload function associated with an xmlHttpRequest.
Consider this:
const req = xmlHttpRequest()
req.open()
req.send()
req.onload = function() {
const data = req.responseText
return data // this doesn't work at all
}
const data = req.onload() // cannot do this
I have found this code in the challenges and it works very well. But I wonder, is it possible to use data outside of the function ? I’ve tried returning it and then calling req.onload but that doesn’t work at all. In the examples I notice that the downloaded data are attached to some DOM element. Is that always the way to go or could I put the downloaded data into a variable to do things with it first?
Another question, req.onload defines a function but I don’t see it being called anywhere, so how come data is being downloaded?
Anything you want to do with the data, you must be done inside the onload
method function. You can always create more functions that do other things with the data and call them from within the function.
const req = xmlHttpRequest()
The call to xmlHttpRequest
returns an object and assigns it to req
with access to various methods like open
, send
, and onload
. The onload
is not something the user calls explicitly. Instead, when you assign the function to it, that function is the callback that is executed when the request completes.
Not really related to your question, but I would suggest using the fetch API if possible. It’s much cleaner, especially when using async/await.
1 Like
Thank you, calling functions inside onload works very well and allows me to separate things. Didn’t know that about the callback, makes complete sense now.
Greets,
Karin
Hi,
Will try this out, these .then statements are very clean and much more readable than calling functions inside another function.
Greets,
Karin