我以前遇到过这个问题,但人们不断误解我的问题。我会再试一次。我有一个bootstrat按钮,点击时javascript使用ajax发送表单。它工作正常,但我无法添加任何东西来清除表单,然后隐藏div。我有代码可以工作,但它出于某种原因发送表单两次(不包括但可以,如果你愿意)?很抱歉重新发布类似的问题,但人们不断给我相同的代码,但根本不起作用。我认为它与按钮类型有关吗?
JS代码是:
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevent default submission of the form after clicking on the submit button.
return false;
});
});
按钮是:
<button name ='send' value="Send" type='submit' class='btn btn-primary'>Finish</button>
答案 0 :(得分:0)
这是制作假AJAX请求的代码。它将output_message替换为Processing ...并替换为Message Sent!一旦完成。
$(document).ready(function() {
$('#btn-finish').on('click', function(event) {
event.preventDefault();
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
setTimeout(function() {
console.log("fake ajax");
$('.output_message').text('Message Sent!');
// This will clear out form field values.
// resetForm($('#myform')); // by id, recommended
// This will hide your element
// $('#myform').hide();
}, 5000);
});
});
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn-finish" name='send' value="Send" type='submit' class='btn btn-primary'>Finish</button>
<div class="output_message"></div>
&#13;
答案 1 :(得分:0)
以下是来自w3schools.com的重置表单脚本应该可以使用
$(document).ready(function(){ $('#btn-finish')。on('click',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
document.getElementById(form.attr('id')).reset();
document.getElementById(form.attr('id')).style.display="none";
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevent default submission of the form after clicking on the submit button.
return false;
});
});
答案 2 :(得分:0)
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
//code to clear form and hide div comes here
$("#divid").hide();
} else {
$('.output_message').text('Error Sending email!');
}
},
complete: function(){
//code to clear form and hide div comes here
$("#divid").hide();
}
尝试放置代码以隐藏和清除表格,如上所述。如果ajax响应成功或错误,默认情况下如果要隐藏,则使用上述完整功能中的代码。发表你的评论。