How to check if a file exists in javascript?

旧巷老猫 提交于 2019-11-28 12:44:39
redsquare

You can use the ajaxComplete event, whis gives you access to the xhr object which you can query the status of the request e.g a status of 404 will mean the file does not exist.

More Info in the docs http://docs.jquery.com/Ajax/ajaxComplete#callback

Test here http://pastebin.me/48f32a74927bb

e.g

$("#someDivId").ajaxComplete(function(request, settings){
    if (settings.status===404){
        //redirect here
    }
});

@PConroy's solution works, but it does the same thing for all failed ajax requests.

If you need this on a per request basis - i.e. if the first request fails it goes to X page and if the second fails go to Y, then you need to do this using the error handle in the $.ajax function:

http://jsbin.com/iwume

(to edit: http://jsbin.com/iwume/edit)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!