jQuery在特定函数上加载div或仅在表单提交上加载div

时间:2014-01-21 23:28:34

标签: javascript jquery loading

我想在使用jQuery提交表单后实例化一个加载图像。

我发现如何做到这一点并且工作正常,但总是在页面上完成所有jQuery请求。

这是一个例子: How can I create a "Please Wait, Loading..." animation using jQuery? 或者在这里 How to show loading spinner in jQuery?

有没有办法可以达到同样的效果,但只有在我提交表格时?

或者有没有办法将它附加到特定的功能,所以它只在这些功能上运行“加载”图像?

我在页面上有这个功能(还有其他jQuery函数),并且只想在这个函数上附加“加载”图像:

 <script>
function send_temp(form) {
  jQuery.post('editor.php?bar=<?php echo $id?>', jQuery(form).serialize(),function(data) {
  jQuery('#editor').html(data);
  });
}
</script>

我提交表格时会调用该函数。

感谢您提供任何帮助或建议。

1 个答案:

答案 0 :(得分:2)

其他问题的答案显示了在AJAX执行时如何在页面范围内执行此操作。您只想在逐个表单的基础上进行此操作。

要使用现有代码执行此操作,可以使用jqXHR.always方法为jQuery.post返回的jQuery XHR对象实现函数:

function send_temp(form) {
    // Show an element containing your spinner
    $('#loadingSpinner').fadeIn();

    // Submit the form, as you were before; attach 
    jQuery.post('editor.php?bar=<?php echo $id?>', jQuery(form).serialize(),function(data) {
        jQuery('#editor').html(data);
    }).always(function(){
        // Request complete, hide the element containing your spinner
        $('#loadingSpinner').fadeOut();
    });
}

请求完成后,将调用jqXHR.always处理程序的回调函数;无论是成功还是失败。