Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Script Tags for JSON requests... detecting if there is a XXX error?

I do a bunch of json requests with dynamic script tags. Is it possible to detect if there's an error in the request (eg. 503 error, 404 error) and run something on detection of the error?

like image 708
rawrrrrrrrr Avatar asked Sep 18 '09 20:09

rawrrrrrrrr


2 Answers

use ajax instead. AFAIK there is no way to detect if a script tag loads or not, and if not, why it didn't load. Using ajax you can load the json and it will tell you why it didn't load.

Using a library like jQuery this becomes very simple:

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script",
  error: function(xhr, error, exception){
    alert(xhr.status); //Will alert 404 if the script does not exist
  }
});
like image 139
Marius Avatar answered Sep 19 '22 17:09

Marius


AFAIK, there's no way to access status code of some external asset loaded from the document (such as script, style or image). Even detecting error (via, say, onerror event handler) is not that widely supported across browsers.

If whatever you're loading falls under SOP, use XHR which gives you access to response headers. Otherwise, you can try looking into recently introduced X-domain XHR.

like image 34
kangax Avatar answered Sep 21 '22 17:09

kangax