2013-08-26 108 views
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> 

请帮助。

回答

0

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

事情是这样的:

function submit() { 
    if (document.getElementById("myTextarea").value=='') { 
    alert("Your comment is too short."); 
    } 
    else { 
    document.getElementById("myForm").submit(); 
    } 
} 
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> 
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. 
    } 
); 

希望这有助于:)

+0

我很困惑,什么样的代码的URL的一部分一样。你能解释一下吗? –

相关问题