【发布时间】:2012-02-06 07:03:34
【问题描述】:
我的 jsp 页面中有两个文本框。在用户按下 TAB 键时在第一个文本框中输入数据后,然后自动控制将调用一个 servlet(在 javascript 中)然后将填充第二个文本框。任何帮助表示赞赏。
【问题讨论】:
标签: javascript jquery ajax servlets
我的 jsp 页面中有两个文本框。在用户按下 TAB 键时在第一个文本框中输入数据后,然后自动控制将调用一个 servlet(在 javascript 中)然后将填充第二个文本框。任何帮助表示赞赏。
【问题讨论】:
标签: javascript jquery ajax servlets
您可以订阅第一个文本框的 .keydown() 事件,如果键是 TAB,则触发对 servlet 的 AJAX 请求:
$(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。
【讨论】:
no wrap(head) 演示的回答。您需要做的就是将您的代码包装在$(document).ready(function() { ... }); 或$(function() { ... }); 中。这将确保 .keydown 事件注册仅在 DOM 完全加载且所有元素都存在时才会发生。如果您将此脚本放在关闭 </body> 之前,则不需要它。
$('#text2').val('some value'); 的 AJAX success 回调中所做的。
使用keycode 在javascript 中捕获TAB 按键。然后使用ajax调用来调用你的servlet
关于 ajax 的更多信息
【讨论】:
你可以试试这个。只需调用您的函数,该函数将在第二个文本框模糊事件上填充第二个文本框。
$('#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);
}
});
});
希望对你有帮助
【讨论】: