Javascript 使用jQuery拦截表单提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14881881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
intercept form submit with jQuery
提问by PogoMips
I want to intercept a submit via jQuery and first check if a file is present on the server. If it's present continue with the request, if not display a message and don't send the request. This is what I have:
我想通过 jQuery 拦截提交并首先检查服务器上是否存在文件。如果存在则继续请求,如果不存在则显示消息并且不发送请求。这就是我所拥有的:
$("#methodForm").submit(function(e){
checkIndex('upload/segments.gen').done(function() {
return true;
}).fail(function () {
e.preventDefault();
alert("No index present!");
return false;
});
});
this is the checkIndex():
这是checkIndex():
function checkIndex(file){
return $.ajax({
url : file,
type:'HEAD'
});
}
What happens is this: The file is present on the server, but the checkIndexreturns with fail. First I see the alert popup and then it continues and sends the post request to the server.
发生的情况是:该文件存在于服务器上,但checkIndex返回失败。首先我看到警报弹出窗口,然后它继续并将发布请求发送到服务器。
I use the checkIndex()for other purposes as well where it works like expected so I'm pretty sure the error is somewhere in the submit routine. But I can't find out what's wrong with it.
我也将checkIndex()用于其他目的,它可以像预期的那样工作,所以我很确定错误在提交例程中的某个地方。但我无法找出它有什么问题。
回答by Kevin B
You can't return out of a callback to an asynchronous method(such as ajax). Instead, prevent the submit all together, then submit it when you are ready.
您不能从回调中返回异步方法(例如 ajax)。相反,不要一起提交,然后在准备好后提交。
$("#methodForm").submit(function(e){
e.preventDefault();
var form = this;
checkIndex('upload/segments.gen').done(function() {
form.submit(); // submit bypassing the jQuery bound event
}).fail(function () {
alert("No index present!");
});
});
回答by adeneo
It does'nt really work like that, checkIndex is asynchronous, so by the time it returns anything, the form is submitted, and the return statements are in a different scope as well, try something more like this:
它不是真的那样工作,checkIndex 是异步的,所以当它返回任何东西时,表单被提交,并且返回语句也在不同的范围内,尝试更像这样的东西:
$("#methodForm").submit(function(e){
e.preventDefault(); //prevent submit
var self = this;
checkIndex('upload/segments.gen').done(function() {
self.submit(); //submit if ajax OK
}).fail(function () {
alert("No index present!");
});
});

