Reputation: 289
I am loading an external JSON
file with $.ajax()
, and I am puzzled as to why my error function will only execute a console.log
, or alert, but nothing else? In my example, if the JSON
is found, the screen turns blue. If the JSON
is not found (i.e. I change the name of the test.js
file to something that doesn't exist), the screen should turn red, but this isn't happening. What's wrong with my code?
$.ajax({
url: 'test.js',
dataType: 'json',
timeout: 3000,
success: function( data ) { success() },
error: function( data ) { fail() }
});
function success(){
$("body").css("background", "blue"); //this works!
console.log("success"); //this works!
}
function fail(){
$("body").css("background", "red"); //this doesn't work :(
console.log("fail"); //this works!
}
Thanks,
Upvotes: 0
Views: 264
Reputation: 2188
If you were to write the above in pure js you'd need to specify almost the same parameters, just now you know specifically what happens and why it does or doesn't work because you can examine everything and it's not obscured by jQuery methods. note: the switch structure is my personal preference, most people do it with a (readyState === 4 && status === 200)
but I always like to keep the ability to expand it to a more sophisticated error handling.
var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.timeout = 3000;
xhr.open("GET","test.js"); //method, url, async [default:true], username, password
xhr.onreadystatechange = function(){
if(xhr.readyState === xhr.DONE){
switch(xhr.status){
case:200
success(xhr);
break;
default:
failure(xhr);
break;
}
}
}
xhr.send();
function success(request){
document.body.style.background = "blue";
console.log(request.status,request.statusText); //> 200 "OK"
}
function failure(request){
document.body.style.background = "red";
console.log(request.status,request.statusText); // reason for error
}
since it's not a jQuery answer and therefore totally off topic I know I'm going to get a ton of downvotes, but I'm ok with that. I'll just have to answer a bunch of other questions to make up for the rep loss.
Upvotes: 1