单击提交按钮后显示加载gif?

9 html javascript jquery

我试图在用户点击表单上的提交后显示加载gif.

我无休止地搜索一个很好的教程,展示它是如何完成的.

我在那里走了一半但是gif没有足够长的时间,任何人都知道一个好的教程或者脚本需要完成这个.

Pao*_*ino 18

这很简单.你有一个最初隐藏的图像:

<img src="myloadingimage.gif" style="display: none;" id="loading_image">
Run Code Online (Sandbox Code Playgroud)

你发了一个AJAX请求:

$('#loading_image').show(); // show loading image, as request is about to start
$.ajax({
    url: '..',
    type: '..',
    complete: function() {
        // request is complete, regardless of error or success, so hide image
        $('#loading_image').hide();
    }
});
Run Code Online (Sandbox Code Playgroud)

我保证,这不是火箭科学.:)

编辑:回应你的评论,这使用jQuery.你把jQuery标签放在一起,所以我认为没问题.

我还注意到我没有完全解决你的原始问题,也就是说你想要显示加载条的大概是常规形式.如果您的表单标记的ID为"myform",则应执行以下操作:

$('#myform').submit(function() {
    $('#loading_image').show(); // show animation
    return true; // allow regular form submission
});
Run Code Online (Sandbox Code Playgroud)

你也可以抛出这样的一行:

$(':submit',this).attr('disabled','disabled');
Run Code Online (Sandbox Code Playgroud)

如果您想阻止用户多次点击提交.这仍然应该在服务器端验证,但它是一个很好的表面防御屏障.


Spl*_*iFF 3

您可以在提交后使用 setTimeout 重新加载 gif (myImg.src = myImg.src;) 来执行此操作。

function wait_animation()
{
    var myMsg = "Sending form data to server... Please Wait...";
    window.status = myMsg;
    msg("<img name='wait' src='/all/images/wait.gif' height=7 width=78> " + myMsg);
}

function long_wait_animation()
{
    var myMsg = "Still sending... You are uploading large files and we have not yet received " +
                            "all the information. Unfortunately, Internet Explorer sometimes interprets " +
                            "this delay as a server error. If you receive a 'Timeout' or 'Site not found' " +
                            "error please click your 'Back' button and try sending less files.";
    window.status = "Still sending ...";
    msg("<img name='wait' src='/all/images/wait.gif' height=7 width=78> " + myMsg);
}

// Generic onSubmit handler
function form_on_submit( myForm )
{
    form_check_lists( myForm );
    if (form_errors.length != 0) {
        err(    'There are some problems with the information you entered:' +
                    '<ul><li>' + form_errors.join('<li>') );
        form_enable_submit(myForm); // re-enable submit (so user can retry)
    } else {
        hideLayer('err');
        window.status = "Uploading Data... Please Wait...";
        form_disable_submit(myForm); // function that prevents double-submissions
        window.setTimeout("wait_animation()", 10);              // 1/100th 
sec (must happen after submit)
        window.setTimeout("long_wait_animation()", 60*1000); // 60 secs
        myForm.submit();
    }
    // reset form errors
    form_errors = new Array();
    return false;   // false=don't submit (because we probably just submitted it).
}
Run Code Online (Sandbox Code Playgroud)

上面的代码基本上做同样的事情,除了 msg() 使用innerHTML 添加动画 gif,而不是更改现有 gif 的源。但概念是相同的,您需要在提交后加载 gif,并且只能使用 setTimeout 来执行此操作(因为否则 IE 会阻止新脚本)。