0

我正在为我的网站制作评论功能,并且需要这样做,以便在该人提交评论(并且包含错​​误)后,它会在不刷新页面的情况下显示错误。我对 AJAX/JQuery 几乎一无所知,所以我需要一些帮助。

这是我到目前为止所拥有的:

<?php
  if(isset($_POST['reply_submit'])) {
    $reply = $_POST['new_reply'];
    $reply_message = "";

    if(empty($reply)) {
      $reply_message = "Your comment is too short.";
    }
  }
?>

<html lang="en">
  <body>
    <form class="no-margin" method="POST" action="">
      <textarea name="new_reply" placeholder="Write a reply..."></textarea>
      <button name="reply_submit" class="btn post-button" type="submit">Post' . (isset($reply_message) ? '<div class="comment-warning">' . $reply_message . '</div>' : '') . '</button>
    </form>
  </body>
</html>

所以我需要它做的是,如果该人的评论框不符合条件(在本例中为空字段),我需要它在不刷新页面的情况下显示此错误行:

<button name="reply_submit" class="btn post-button" type="submit">Post' . (isset($reply_message) ? '<div class="comment-warning">' . $reply_message . '</div>' : '') . '</button>

请帮忙。

4

3 回答 3

0

使用 Javascript

HTML:

<button name="reply_submit" class="btn post-button" onclick="validate()">Post comment</button>

Javascript:

<script>
function validate(){
  reply = document.getElementById('new_reply').value;
  if (reply==null || reply=="")
    {
    alert("Your comment is too short.");
    return false;
    }
  }
</script>
于 2013-08-26T23:59:54.247 回答
0

我认为通过 Javascript 在客户端进行验证更容易。与其简单地使用 类型的按钮,不如submit编写一个函数并将其绑定到按钮的onclick()事件。

像这样的东西:

function submit() {
  if (document.getElementById("myTextarea").value=='') {
    alert("Your comment is too short.");
  }
  else {
    document.getElementById("myForm").submit();
  }
}
于 2013-08-26T23:53:48.173 回答
0

对于空字段或输入框长度等基本验证,您可以使用 jQuery 验证插件 -- http://jquery.bassistance.de/validate/demo/或编写自己的内容。

您可以使用 jQuery 进行更好的 AJAX/错误处理。在此处查看 jQuery AJAX 的文档——http: //api.jquery.com/jQuery.ajax/

$.ajax({
  url: "test.html", //URL to send the request
  success: function() {
    //do something. This is fired when your response is successful
  },
  error: function() {
    //highlight the field that has error or do something else here.
  }
);

希望这可以帮助 :)

于 2013-08-27T00:17:45.400 回答