2012-08-23 27 views
0

我想在我的網站上做一個評論系統。我管理ajax部分,並將註釋從表單提交到被調用的php文件,然後將數據存儲在mysql數據庫中。存儲後,數據將被附加到已有的已有註釋。jQuery的.post事件逐步發射

我遇到的問題是,如果您在之前的一個帖子後發佈另一條評論,則會添加兩條評論。再做一次,下一次增加三次,依此類推。我想我得到了jquery錯誤的地方,但似乎無法找到它。

下面是我使用的形式:

<form class="short style" id="postnewscomment" name="postnewscomment" onsubmit="javascript:postnewscomments();"> 
    <textarea style="width:95%;" name="commenttext" required data-required="true" placeholder="Uw comment" /></textarea> 
    <input type="hidden" name="task" value="addcomment" /> 
    <input type="hidden" name="postername" value="<? echo $_SESSION['user_id']; ?>" /> 
    <input type="hidden" name="newsid" value="<? echo $newsid; ?>" /> 
    <div class="button"> 
     <button value="postnews" name="Submit" type="submit">Add Comment</button> 
    </div> 
    </form> 

下面是由窗體調用我的jQuery代碼:

function postnewscomments() { 
    $("#postnewscomment").submit(function(e){  
     e.preventDefault(); 
    var hasError = false; 
     var url = "postnewscomments.php"; 
    var texttopost = "#postnewscomment"; 
    if(hasError == false) { 
     $.post(url, $(texttopost).serialize() ,function(data) { 
      $(data).hide().appendTo("#newscomment").fadeIn(1000); 
     // code to reset form values to empty 
       $('#postnewscomment').each(function(){ 
       this.reset(); 
     }); 
      }); 
    } 
    return false; 
    }); 
} 

回答

0

看那submit()方法:

綁定「提交」JavaScript事件的事件處理程序,或觸發元素上的該事件。

所以應該只調用一次(當頁面加載時)而不是每次提交。

http://api.jquery.com/submit/

+0

它更改爲 '$(窗口).bind( 「負載」,函數(){ \t postnewscomments();} );'這就是訣竅!不能相信它有多簡單,而且我之前沒有找到這個......對於JS和Jquery來說還是新手,但是這並不容易:(Thx的幫助! –