在页面之间显示“页面加载”消息

时间:2012-05-22 16:54:50

标签: javascript jquery html lightbox modal-dialog

我的网站上有form,提交后会将用户从Page1.html转移到Page2.html

我想在提交的表单和“Page2 loading”之间显示一条消息。

有人能为我提供一个例子吗?

2 个答案:

答案 0 :(得分:1)

如果你的表单通过ajax提交数据,那么你可以试试这个:

$('form#myform').submit(function(e) {
   e.preventDefault();
   $('#message').html('Sending....');  // #message may be a div that contains msg
   $ajax({
     url: 'url_to_script',
     data: 'your_data',
     success: function(res) {
       // when submit data successfully then page reload
       window.location = 'page2.html'
     }
   });
});

答案 1 :(得分:1)

您希望通过标准表单提交来完成您的工作。

您需要使用ajax提交表单,并在等待回复时显示“请稍候”消息。收到回复并验证确定后,您可以将用户重定向到您现在调用第2页的页面。

通过ajax提交表单的最简单方法是将serialize转换为字符串并传递给它。然后,您将需要一个页面来处理接收的数据,并返回OK或ERR。

然后,JS将需要解密下一步行动。

这未经过测试,但已从各种工作项目中复制和粘贴。 您需要download and include the json2.js project.

<强>第1页

<div id='pleaseWait'>Please Wait...</div>
<form id="theForm" onsubmit="doAjaxSubmit();">
    <input type='text' name='age' id='age' />
    <input type='submit' value='submit'>
</form>

<script type="text/javascript">
    function doAjaxSubmit(){
        var j = JSON.stringify($('#theForm').serializeObject());

        $('#pleaseWait').slideDown('fast');
        $.post('processor.php?j=' + encodeURIComponent(j), function(obj){
            if(obj.status=='OK'){
                window.location='page2.php';
            }else{
                $('#pleaseWait').slideUp('fast');
                alert('Error: ' + obj.msg);
            }
        }, 'json');
        return(false);
    }    


    $.fn.serializeObject = function(){
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
</script>

<强> processor.php

<?php

    $j=json_decode($_POST['j'], true);


    if ((int)$j['age']<=0 || (int)$j['age']>120){
       $result = array('status'=>'ERR', 'msg'=>'Please Enter Age');
    }else{
        //Do stuff with the data. Calculate, write to database, etc.
        $result = array('status'=>'OK');
    }
    die(json_encode($result));
?>

这与下面的答案(@thecodeparadox)非常相似,但是我的示例显示了如何在不必手动构建数据对象的情况下传递整个for,显示了如何在PHP端进行验证返回相应的JSON数据以重定向用户,或显示错误,并使用动画显示消息。

相关问题