Roman Šimr
Roman Šimr

Reputation: 47

Detect JSON exist

I have question about chechking file exists.

I have this piece of code.

function fileExists(url) {
  if (url) {
    var req = new XMLHttpRequest();
    req.open('GET', url, false);
    req.send();
    console.log("exists");
    return true;
  } else {
    console.log("no exists");
    return false;
  }
}

But it says me that file is exists. But it doesn't exists. In fact on my URL is 404 error XML file. Is possible somehow detect if requested URL is JSON? I need to return true only if checked file is JSON.

Thank you

Upvotes: 0

Views: 155

Answers (1)

Zach Bloomquist
Zach Bloomquist

Reputation: 5889

Since this is a synchronous request, you can just try to parse the responseText you get back and if it fails to parse, you know it's not JSON:

        var res = req.responseText;
        try {
             res = JSON.parse(res);
             console.log('json', res);
        } catch (e) {
             console.log('not json')
        }

If it were not a synchronous request, this would work:

If you look at the XMLHttpRequest docs, you'll see that in order to receive data back from an XMLHttpRequest, you need to add a callback function:

xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
        // Request finished. Do processing here.
    }
}

If you wanted to check if your request is JSON, you could do this:

xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
        var res = this.responseText;
        try {
             JSON.parse(res);
             console.log('json', res);
        } catch (e) {
             console.log('not json')
        }
    }
}

Upvotes: 4

Related Questions