在页面之间显示'Page Loading'消息



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

我想在正在提交的表单和"Page2 加载"之间显示一条消息。

有人可以给我举个例子吗?

如果您的表单通过 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'
     }
   });
});

您要做的事情无法通过标准表单提交来完成。

您需要使用 ajax 提交表单,并在等待响应时显示"请稍候"消息。收到响应并验证为正常后,您可以将用户重定向到您现在称为 page2 的页面。

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

然后,JS将需要破译下一个操作。

这不是经过测试的,而是从各种工作项目中复制和粘贴的。您需要下载并包含json2.js项目。

页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>

处理器.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 数据以重定向用户或显示错误, 并使用动画来显示消息。

相关内容

最新更新