我有一个ajax调用,在成功之后,它强制刷新或重新提交当前页面。我有e.preventDefault来阻止它,所以这很令人困惑。当我单击表单上的提交时,我不想在页面上重新提交或刷新,我想调用ajax并将其内容放在页面上。这是asp mvc4。我知道它确实调用了方法并从中获得了结果。我在成功通话中发出的提示会弹出并显示正确的内容,但在我点击确定后,它看起来就像是重新提交或刷新页面。
<form id="multiple3And5Form" action="">
<div class="row">
<div class="col-md-4">
<p>Multiples of 3 and 5</p>
</div>
<div class="col-md-2">
<input type="number" name="multiple3And5" id="multiple3And5" min="0">
</div>
<div class="col-md-4">
<p id="multiple3And5_answer">
</p>
</div>
<div class="col-md-2">
<input type="submit" name="submit_multiple3And5" id="submit_multiple3And5" value="Submit">
</div>
</div>
</form>
<script type="text/javascript">
$('#multiple3And5Form').submit(function (e) {
e.preventDefault;
var inputData = $(this).serialize();
$.ajax({
method: "POST",
url: '@Url.Action("multiple3And5Method")',
data: inputData,
success: function (result) { $('#multiple3And5_answer').html("Answer: "+result); alert(result); },
error: function (error) { alert(error.status); $('#multiple3And5_answer').html(error); }
});//end ajax
}//end function(e) near .submit
);//end submit
</script>
public JsonResult multiple3And5Method(int multiple3And5)
{
int answer = 0;
for(int i = 1;i<multiple3And5;i++)
{
if(i%3==0 | i%5==0)
{
answer += i;
}
}
return Json(answer, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:2)
关于Ajax成功提交表单
<form id="multiple3And5Form" action="">
<div class="row">
<div class="col-md-4">
<p>Multiples of 3 and 5</p>
</div>
<div class="col-md-2">
<input type="number" name="multiple3And5" id="multiple3And5" min="0">
</div>
<div class="col-md-4">
<p id="multiple3And5_answer">
</p>
</div>
<div class="col-md-2" style="display: none">
<input type="submit" name="submit_multiple3And5"
id="submit_multiple3And5" value="Submit">
</div>
</div>
</form>
<div class="col-md-2">
<input type="button" name="btnNmae" id="btnId" value="Submit">
</div>
JS
$('#btnId').click( function(e) {
var numVal = $('#multiple3And5').val();
$.ajax({
method: "POST",
url: '@Url.Action("multiple3And5Method")',
data: { inputData: numVal },
success: function (result) {
$('#multiple3And5_answer').html("Answer: " + result); alert(result);
$('#multiple3And5Form').submit();
},
error: function (error) { alert(error.status); $('#multiple3And5_answer').html(error); }
});//end ajax
});