2011-03-17 69 views
0

我使用AJAX動態獲取評論。這個隱藏的DIV填充了評論和表格,然後顯示出來。該表單用於向當前查看的評論列表添加新評論(通過AJAX返回)。從AJAX表格獲取文本內容

我希望用戶能夠查看DIV中的註釋,然後將註釋從DIV本身添加到DIV中。

一切正常,但我無法獲得評論的文本字段的內容。

我有$('#submit_comment').live('click', function(e) ...用於檢測AJAX表單提交按鈕。這工作。我只是不能在文本框中獲取字符串...這是非常煩人的,我嘗試了很多方法,如`var comment = $('#new_comment')。val();' - 這不起作用。

我的HTML包括以下內容:

<form id="new_comment" name="new_comment" method="get" action="comments.php"> 
       <input type="hidden" id="trackID" value="' . $track . '"> 
       <input type="text" size="25" id="new_comment_text" /><span style="text-align:right"> 
       <input type="submit" value="Comment" id="submit_comment"/></span> 
      </form> 

它是從comments.php文件中回顯,所有持有浮動DIV中。

如何從AJAX DIV窗體中獲取文本字段的內容?

以下是完整的AJAX調用:

$('#submit_comment').live('click', function(e) { 


     e.preventDefault(); 

     var comment = $('#new_comment_text').val(); 
     alert(comment); 

     if (comment != '') { 

      $('#loading').show(); 
      $('#commentsPanel').hide(); 
      // loading = true 

      var track = $('#trackID').val(); 

      alert(track); 
      var data = 'track=' + track + '&isComment=true&comment=' + comment; 
      alert(data); 
      $.ajax({ 
       url: 'comment.php', 
       type: 'GET', 
       data: data, 
       cache: false, 
       success: function (comments_html) { 
        alert('submit_comment'); 
        $('#commentsPanel').html(comments_html); 
        $('#commentsPanel').show(); 
        $('#loading').hide(); 
       } 
      }); 
     } 
     else { 

     } 
    }); 
+0

重現問題:使用動態內容 – mattsven 2011-03-17 18:25:25

+0

整蠱其實它是具有相同的值作爲ID爲文本區域的名稱。我改變了這一切,它無法正常工作....任何其他信息? – Alex 2011-03-17 18:40:25

回答

2

難道你的動作與網址不完全相加,因爲缺少s

form id="new_comment" name="new_comment" method="get" action="comments.php"

$.ajax({ 
      url: 'comment.php', 
+0

NVM ..只是閱讀其他職位的額外評論...顯然,這就是它了..哈哈 – newbie 2017-09-26 18:11:13

3

你的表格和文字輸入都具有相同的ID,使文字輸入元素都有一個唯一的ID和名稱。

<form id="new_comment" name="new_comment" method="get" action="comments.php"> 
    <input type="hidden" id="trackID" value="' . $track . '"> 
    <input type="text" size="25" id="new_comment_text" name="new_comment_text" /><span style="text-align:right"> 
    <input type="submit" value="Comment" id="submit_comment"/></span> 
</form> 

...

var comment = $('#new_comment_text').val(); // Should be the input value. 

的jsfiddle - http://jsfiddle.net/L74hu/

+0

當http://jsfiddle.net/ – Alex 2011-03-17 18:30:03

+0

@AlexW我不知道這是什麼意思,我做了一個JSFiddle在我的答案中鏈接,這不是你想要的嗎? – 2011-03-17 18:31:26

+0

我在這裏使用了一個AJAX'd表單(因此使用'.live()')..我意識到.val()通常會得到內容......它不工作,我已經徹底地測試了我的代碼... confused :( – Alex 2011-03-17 18:38:46

0
var comment = $('#new_comment').val() 

是不行的(或可能不是),因爲你有兩次相同的ID:

form id="new_comment" 
input id="new_comment" 

你應該選擇一個不同的ID,它應該是好的

+0

不有所作爲:( – Alex 2011-03-17 18:39:04

+0

@Alex在這種情況下,你爲什麼要接受這個答案嗎? – showdev 2017-09-26 19:46:00