最简单的例子是,当用户单击提交时,我想显示一个div,其中有一个gif指示消息正在发送。
Javascript:
//Send mail
$("div.contato-pedidooracao form").submit(function () {
$(".sending").show(); //HERE.. DONT WORK!! why??
$(".contato-pedidooracao form").hide(); //THIS WORKS!!
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "Contato/SendMail",
data: dataString,
dataType: "json",
success: function (data) {
$(".sendMessage").empty();
$(".sendMessage").append("<p>Mensagem enviada com sucesso</p>")
$(".sendMessage").append("<p>Rezaremos por você!</p>")
$(".sendMessage").show();
},
error: function (xhr, ajaxOptions, thrownError) {
$(".sendMessage").empty();
$(".sendMessage").append("<p>Ocorreu um erro ao tentar enviar a mensagem</p>")
$(".sendMessage").append("<p>Por favor, tente novamente mais tarde.</p>")
$(".sendMessage").show();
$(".contato-pedidooracao form").show();
}
});
$(".sending").hide();
event.preventDefault();
});
HTML
<div class="content contato-pedidooracao">
@using (Html.BeginForm())
{
<p>Conte-nos seu pedido</p>
<div class="inline">
@Html.Label("name", "Nome:")
@Html.TextBox("name", "")
</div>
<div class="inline">
@Html.Label("phone", "Telefone:")
@Html.TextBox("phone", "", new { @class = "phone" })
@Html.TextBox("cel", "", new { @class = "phone" })
</div>
<div class="inline">
@Html.Label("email", "e-mail:")
@Html.TextBox("email", "", new { @class = "email" })
</div>
<div class="inline">
@Html.Label("message", "Mensagem:")
@Html.TextArea("message", "")
</div>
<div class="submit">
<input type="submit" value="Enviar" title="Enviar" />
</div>
}
<div class="message sending">
<p>Enviando mensagem</p>
<img src="@Href("~/Images/ajax-loader.gif")" alt="Enviando..." />
</div>
<div class="message sendMessage"></div>
</div>
我不知道这是否相关。。但是CSS的一部分:
div.column > div.contato-pedidooracao > div.message
{
display:none;
}
.sending, .sendMessage
{
text-align:center;
}
处理平均需要5秒,但div.sending
不会在此时间间隔内出现。。
因为AJAX是异步的,JS不会等待它。所以放在AJAX后面的$(".sending").hide();
实际上是在$(".sending").show();
之后执行的。
尝试将$(".sending").hide();
放在AJAX中成功和错误函数的末尾。