使用AJAX向用户显示样式化验证消息

时间:2014-08-27 17:41:39

标签: javascript php jquery ajax

我是AJAX和jQuery的新手,为了测试,我创建了这个简单的代码。当用户输入名字及其姓氏时,会显示一条消息,其中显示{strong>蓝色颜色为Thanks for entering everything correctly!,并且如果用户忘记输入名字及其姓氏,则会显示错误,其中显示{strong>红色颜色中的You didn't entered anything或类似的内容是的我知道这听起来很愚蠢,但这只是测试......所以这是我的代码:

  

change_name.php

function displayError($error)
{
    // Display a div with a class of error, We style it using CSS
    echo "<div class='error'>$error</div><br>";
}

function displayMessage($message)
{
    // Display a div with a class of message, We style it using CSS
    echo "<div class='message'>$message</div> <br>";
}


if (isset($_POST['first_name']) && isset($_POST['last_name'])) {
    if (empty($_POST['first_name']) && empty($_POST['last_name'])) {
        displayError('You didn\'t entered anything!');
    } else if (empty($_POST['first_name'])) {
        displayError('You didn\'t entered your first name!');
    } else if (empty($_POST['last_name'])) {
        displayError('You didn\'t entered your last name!');
    } else {
        displayMessage('Thanks for entering everything correctly!');
    }
}
  

的JavaScript

$(document).ready(function(){
    $('#nameChange').on('submit', function (e) {

        $.ajax({
            type: 'POST', 
            url: 'ajax/change_name.php',
            data: $(this).serialize(),
            success: function(data) {
               $('.result').empty().append(data);
            }
        });

        e.preventDefault();
    });
});
  

的index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery AJAX</title>

    <style>
        .message {
            font-family: sans-serif;
            color: #00AAE9;
            font-size: 16px;
        }

        .error {
            font-family: sans-serif;
            color: #E70000;
            font-size: 16px;
        }
    </style>
</head>
<body>

    <form action="ajax/change_name.php" method="POST" id="nameChange">

        Result: <div class="result"></div>


        <label for="first_name">First Name:</label>
        <input type="text" name="first_name" id="first_name">
        <br>

        <label for="last_name">Last Name:</label>
        <input type="text" name="last_name" id="last_name">        
        <br>

        <input type="submit" name="change_name" value="Change" id="change_name">
    </form>


    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="js/init.js"></script>
</body>
</html>

我的问题是:显示<div>然后添加一个类是一个好习惯,那么你可以使用CSS设置它的样式吗?这样做有更好的方法吗?您是否只能返回JSON响应并使用JavaScript访问它?

谢谢!

1 个答案:

答案 0 :(得分:1)

我为每个案例做这个,我需要来自服务器的TRUE / FALSE结果,并附上一些信息:

<强> PHP

// $_POST values are just examples
if ($_SERVER["REQUEST"]=="POST") {
    if (empty($_POST["username"]) || strlen($_POST["username"])<3) {
       echo json_encode(array("result"=>FALSE,"class"=>"fail","message"=>"Your username can't be empty or less than 3 characters"));
       return;
    }
    ...
    echo json_encode(array("result"=>TRUE,"class"=>"success","message"=>"Success");
    return;
}

<强> JS

$.ajax({
   type: 'POST', 
   url: 'ajax/change_name.php',
   data: $(this).serialize(),
   dataType: "JSON",            <----
   success: function(data) {
      $('.result').removeClass().addClass("."+data["class"]).html(data["message"]);
   }                                                 --^            ------^
});

这可能看起来有点难看:)尽管