Reputation: 11
This is the sync function.I call it inside an Ajax, but how is synchronous it´s deprecated. ¿Is there any way to run it as if it were asynchronous? Or to make it asynchronous? Thanks.
function fetchHeader(url, hdr) {
try {
var req=new XMLHttpRequest();
req.open("HEAD", url, false);
req.send(null);
if(req.status== 200){
return req.getResponseHeader(hdr);
}
else return false;
} catch(er) {
return er.message;
}
I've tried that, but it says: response is not defined and callback is not a function.
function fetchHeader(url, hdr, callback) {
try {
var req=new XMLHttpRequest();
req.onreadystatechange = function() {
if(this.status == 200) {
callback(req.getResponseHeader(hdr), req);
}else{
console.log("callback is not called");
}
}
req.open("HEAD", url, true);
req.send(null);
} catch(er) {
return er.message;
}
}
And I call it:
fetchHeader(dirGen+json[i],'Last-Modified', function(header, request) {
if (response.statusCode == 200) {
return header;
console.log(header);
}else {
console.log("Failed answer");
}
});
Upvotes: 1
Views: 60
Reputation: 1421
You don't need to micromanage XMLHttpRequest
anymore. Just listen for the 'load' event. Actually I suggest you switch to fetch
. fetch
returns a promise which will help you build cleaner code for this type of thing. But here is basics of how to call one XHR and then start another after you get a response.
var url1 = 'path/to/file'
var url2 = 'path/to/differentfile'
function onXhrError() {
// ... handle errors
}
xhr1 = new XMLHttpRequest()
xhr1.addEventListener('load', onXhrLoad1)
xhr1.addEventListener('error', onXhrError)
xhr1.open('GET', url1)
xhr1.send()
function onXhrLoad1 (){
var res = this.responeText
function onXhrLoad2 (){
var res2 = this.responeText
// ... do stuff with second response
}
var xhr2 = new XMLHttpRequest()
xhr1.addEventListener('error', onXhrError)
xhr2.addEventListener('load', onXhrLoad2)
xhr2.open('GET', url2)
xhr2.open()
// ... do other stuff with first resoponse
}
Upvotes: 1