【问题标题】:Server side varification after client side done客户端完成后服务器端验证
【发布时间】:2014-06-27 14:21:54
【问题描述】:

假设我有一个登录表单,其中包含两个表单元素,即用户名和密码。但是在客户端验证中,我没有在用户名中设置必需的选项。我的目标是在进行客户端验证之后,我想通过 ajax 从服务器端对此进行验证,其中用户名字段将在服务器端进行验证,如果用户名为空,则 php 检查并作为 json 响应。我想解析数据并显示验证错误,并在登录表单中向不同的 div 元素显示登录身份验证错误消息。但无法得到这个。请帮我解决这个问题。

$(document).ready(function(){

        // initialize validator and add the custom form submission logic
            $("#LoginForm").validator().submit(function(e) {

                    var form = $(this);

                    // client-side validation passed
                        if (!e.isDefaultPrevented()) {


                            $.ajax({
                                type: "POST",
                                url: "process.login.php",
                                data: $('#LoginForm').serialize(),
                                dataType: "json",
                                success: function(msg){

                                    if(parseInt(msg.status)==1)
                                        {   
                                            window.location=msg.txt;
                                        }
                                 }
                            });


                            // prevent default form submission logic
                            e.preventDefault();
                        }
                    });

                });

【问题讨论】:

  • 你有一个缺失的 } 成功:function(msg){
  • 谢谢,更新了这段代码。

标签: php jquery ajax


【解决方案1】:

我猜你想知道 php(服务器)验证响应是如何工作的?

<?php

// your validation here ...

$msg = array("status"=>1, "text"=>"some text here");

echo json_encode($msg);

【讨论】:

    【解决方案2】:

    这可能会有所帮助.. 我不得不在隐藏的表单变量中欺骗您的响应,但您应该获取消息和状态并处理它。同时捕获服务器端错误。

    我还按照您设置的方式修复了您的验证,但您可能需要阅读有关 jQuery 验证器最佳实践的文档。

    http://jsfiddle.net/Xedus129/y6fA3/

    ajax 调用中的错误处理/成功处理:

                success: function (msg) {
                    var status = parseInt(msg.status);
                    var message = msg.message;
                    return handleResponse(status,message);
                },
    
                error: function (xhr, ajaxOptions, thrownError) {
                    //this is a fatal error
                    alert(xhr.status);
                    alert(thrownError);
                }
    

    希望这就是你所问的,从你的问题很难看出。

    【讨论】:

    • 我已经对密码字段进行了客户端验证,即 jquery 检查密码字段是否为空。如果为空则显示错误消息(默认验证错误消息),否则使用这个'if($(this).valid()){'并发布到php页面,如果为空则检查名称字段然后抛出json 格式的 msg,并传递给 jquery 验证器,例如 {'username':'enter the username'}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 2019-01-16
    • 2017-01-26
    • 2010-09-14
    • 2016-10-16
    • 1970-01-01
    相关资源
    最近更新 更多