Detect 404 error from included JavaScript file
I am making a cross-domain JSON(P) call by using JavaScript to add a <script>
tag to the DOM with that URL I want included as the src
. The script being loaded has a callback that calls a function on my page, and the data I want is returned as an argument to the function.
There are 2 catches, though:
- Sometimes the JSONP page will return a 400 or 404 error.
- The same JSONP file can be reques开发者_如何学编程ted multiple times on the same page (each time returning different data)
So, I need to detect when the callback function is not fired (which would indicate that the JSONP file returned an error), but I also need to account for the fact that the same file can be requested twice. Essentially, I need to detect the error in loading the page, but I have to do it before the other files finish loading. And yes, the files should be loaded (or return an error) in the correct order.
One (inefficient) solution:
I could make a bunch of different functions that are requested for each different file load (eg. callbackFunction0, callbackFunction1, etc). That way, I can simply determine when one of the functions didn't fire and have my JavaScript act off of that. However, this would take up a lot of space an be inefficient because I would have to have one callbackFunction for the maximum time the script would be loaded on the same page (this number has no definite value, though, so if I only made 15 functions and the script was requested 20 times, errors would occur).
This was kind of difficult to explain, but hopefully you got the idea. Thanks.
$.ajax have many callback functions which you can utilize.
$.ajax({
url: "test.html?callback=?",
dataType: "jsonp",
success: function(data){
// your logic
}
statusCode: {
404: function() {
alert('page not found');
}
}
});
You could just add a argument to the callbackfunction containing the id/number/position of the script. So something like callbackFunction(1, ...rest of arguments..). No need to create new function-names.
You could detect the error by attaching the onerror event to the script element. Somewhat related: How to trigger script.onerror in Internet Explorer?
To solve this, I made the callback include a variable containing the request number. So the callback might be var requestnumber=0;callbackFunction
. Then I could figure out which request applied to which element. I should have thought of this before.
精彩评论