2012-02-06 34 views
0

我的jsp頁面中有兩個文本框。在用戶按下TAB鍵後在第一個文本框中輸入數據後,自動控制將調用一個servlet(在JavaScript中),然後將填充第二個文本框。任何幫助表示讚賞。從按下TAB鍵的javascript調用servlet

回答

2

你可以訂閱.keydown()事件的第一個文本框的,如果關鍵是TAB觸發一個AJAX請求到servlet:

$(function() { 
    // subscribe to the keydown event 
    $('#text1').keydown(function(e) { 
     // when a key is pressed check if its code was 9 (TAB) 
     if (e.which == 9) { 
      // if TAB was pressed send an AJAX request 
      // to the server passing it the currently 
      // entered value in the first textbox 
      $.ajax({ 
       url: '/someservlet/', 
       type: 'POST', 
       data: { value: $(this).val() }, 
       success: function(result) { 
        // when the AJAX succeeds update the value of the 
        // second textbox using the result returned by the server 
        // In this example we suppose that the servlet returns 
        // the following JSON: {"foo":"bar"} 
        $('#text2').val(result.foo); 
       } 
      });  
     } 
    }); 
}); 

這裏是live demo

+0

thanks..but到位的url,我會寫servlet的名字嗎?你能告訴我,第一個文本框中的.keydown()嗎?請給我演示一個無包裝(頭) – Tom 2012-02-06 07:13:43

+0

@tom的演示,您將編寫servlet配置爲偵聽的url。通常是它的名字。測試首先在您的瀏覽器地址欄中調用url以確保您的servlet正常工作。這是第一步。另外看看我的答案'無包裝(頭)'演示。所有你需要做的就是把你的代碼包裝在'$(document).ready(function(){...});'或'$(function(){...});'中。這將確保'.keydown'事件註冊只有在DOM完全加載並且所有元素都存在時纔會發生。如果你把這個腳本放在''之前,你就不需要它了。 – 2012-02-06 07:15:39

+0

雅..我知道了,只有一個疑問達林。我收到的第二個文本框的值作爲酒吧,我可以放置在第二個文本框的值,如:,我是越來越困惑..請通過解釋 – Tom 2012-02-06 07:24:02

1

你可以試試這個。只需調用您的函數將填充第二個文本框模糊事件的第二個文本框。

$('#secondtextbox').blur(function() { 
    $.ajax({ 
      url: '/someservlet/', 
      type: 'POST', 
      data: { value: $('#firsttestbox').val() }, 
      success: function(result) { 
       // when the AJAX succeeds update the value of the 
       // second textbox using the result returned by the server 
       // In this example we suppose that the servlet returns 
       // the following JSON: {"foo":"bar"} 
       $(this).val(result.foo); 
      } 
     });  
}); 

希望這有助於

+0

謝謝迪帕克...我已經使用了上面提供的相同 – Tom 2012-02-06 13:31:42