2014-02-10 30 views
0
通過

我有以下的AJAX代碼提交名稱/電子郵件/信息參數,以「messageaction.cfm」模板,並顯示原提交頁面上的那些相同的3個參數(正常工作):提交按鈕值不與阿賈克斯

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> 
    <script type="text/javascript"> 
     function submitForm() { 
      $.ajax({type:'POST', url:'messageaction.cfm', data:$('#ContactForm').serialize(), success: function(response) { 
       $('#ContactForm').find('.form_result').html(response); 
      }}); 

      return false; 
     } 
    </script> 

      <form id="ContactForm" onsubmit="return submitForm();"> 
       Name: <input type="text" name="name" value=""><br> 
       Email: <input type="text" name="email" value=""><br> 
       Message:<br> <textarea style="width: 200px; height: 100px;" name="message"></textarea> 
       <br> 
       <input type="submit" name="Choice" id="Choice" value="One"> 
       <input type="submit" name="Choice" id="Choice" value="Two"> 
       <div class="form_result"></div> 
      </form> 

但是,我有2個提交按鈕(「One」和「Two」的相應值),並希望能夠檢測到哪個按鈕被按下。在一個正常的提交表單中(沒有ajax),根據我點擊哪個按鈕,變量「Choice」與相應的「One」或「Two」正確顯示。但在ajax表單中,無論我按哪個按鈕,「選擇」變量只顯示相同的「0」(默認值)。

我已經嘗試了2個其他ajax表單變體,但似乎無法傳遞輸入提交按鈕值的值。我做錯了一定有一些非常基本的東西,但我已經嘗試過所有我能想到的東西。任何建議將不勝感激!

回答

1

由於id是獨一無二的,name屬性應在同一form是唯一的,以及,你應該改變:

<input type="submit" name="Choice" id="Choice" value="One"> 
<input type="submit" name="Choice" id="Choice" value="Two"> 

到:

<input type="submit" name="ChoiceOne" id="ChoiceOne" value="One"> 
<input type="submit" name="ChoiceTwo" id="ChoiceTwo" value="Two"> 

,並與您的AJAX代碼再試一次。確保你這次的目標是正確的:)

+0

菲利克斯,'欣賞小費,但我嘗試過,結果仍然相同。我還刪除了第二個輸入按鈕,以便有一個按鈕「ChoiceOne」,但是當我點擊它時,它仍然沒有傳回值「One」,而是仍然只顯示默認的「0」。這真讓我感到困惑。在標準表單提交中,顯示值「ChoiceOne = One」,但是通過Ajax檢索時,無論我嘗試什麼,它都只顯示「ChoiceOne = 0」。 – user3293560

+0

我也嘗試以下Ajax代碼: \t <腳本類型= 「文本/ JavaScript的」> \t \t $(函數(){ \t \t \t $( '#FF')形式({ \t \t \t。 \t成功:功能(數據){ 的document.getElementById( '數據')的innerHTML =數據; \t \t \t \t。} \t \t \t}); \t \t}); \t \t <表格ID = 「FF」 行動= 「messageaction.cfm」 方法= 「POST」> user3293560

+0

使用document.getElementById('data')。innerHTML的同樣的問題。它不會回傳提交按鈕本身的實際值「One」。 – user3293560

0

submit事件發生時,jQuery.serialize()不知道哪個按鈕被點擊了,所以在生成表單數據時很可能會跳過這些按鈕。

您還必須處理每個按鈕的點擊事件,並手動傳遞按鈕值。

另一種方法是在用戶單擊按鈕時設置隱藏表單字段值,因爲按鈕點擊事件將在表單提交之前得到處理。

+0

感謝您的提示! – user3293560