我有以下情况
这可以用jquery完成吗?
$form.on('submit', function () {
// at this point I can begin the ajax request but there will not be enough time
// for the ajax request to complete, the ajax request will also require a callback
});
是否有处理这种情况的已知模式?
编辑:
我只想澄清我的问题在这里。我无法弄清楚如何在提交事件处理程序中执行ajax请求,因为ajax请求是异步的,表单无论如何都会简单地提交。 $ .ajax提供了一个' async:flase'我需要的选项,解决了我的问题。
由于
答案 0 :(得分:3)
您想使用JQuery ajax调用的success
属性。
如果数据检查未通过,您需要return false;
取消表单提交。
$form.on('submit', function () {
$.ajax({
type: "POST",
url: 'firsturltarget',
data: formData,
success: function (dataCheck) {
if (dataCheck == 'value') {
// Data Check passed finish submitting form
$.ajax({
type: "POST",
url: '/login/spam',
data: formData
});
}
else {
return false; // Data Check invalid, cancel submit
}
}
});
});
答案 1 :(得分:1)
使用
$( "#target" ).submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});
表格
并提交使用
$( "#other" ).click(function() {
$( "#target" ).submit();
});
答案 2 :(得分:1)
首先编写绑定提交事件。
$("#form-id").submit(function(){
//check the input here
$.ajax({
url:"something",
type:"post",
data:{label:value},
success:function(data){
//populate values in hidden field
return true;
},
error:function(){
}
});
});
答案 3 :(得分:1)
据我所知,使用jquery提交表单的最佳方式是
$('body').on('submit', '#FormId', function(event){
event.preventDefault(); //stops execution of default form action
$.ajax({
url : 'localhost/project/controller/method', //type your form submit method path
type : 'post', //your form method...either get or post
data : $(this).serialize(), //by this all input field data will be grabbed
dataType : 'json', //the data type that you want back from your form submit method
success: function(data)
{
//your code after successful submission of your form
}
});
});