在没有页面刷新的情况下在新HTML元素中显示错

时间:2013-08-27 03:05:53

标签: php javascript ajax jquery

我正在尝试为我的网站创建一个评论部分,并且需要这样做以便在此人提交评论后(并且它包含错误),它将显示错误(新的HTML元素)而不刷新页面。我几乎不了解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>

请帮忙。

1 个答案:

答案 0 :(得分:0)

  

HTML 大致相同,添加onsubmit action

<form class="no-margin" method="POST" action="" onsubmit=verify();>
      <textarea name="new_reply" id="new_reply_textarea" placeholder="Write a reply..."></textarea>
...
</form>
<div class=comment-warning></div>
  

<强> JS

function verify()
{
if ($('#new_reply_textarea').is(':empty'))
{
$('.comment-warning').html("Your comment is too short.");
return false;
}
else
{
return true;
}
}