2013-08-26 109 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的一部分一樣。你能解釋一下嗎? –

相關問題