【发布时间】:2013-11-19 07:48:46
【问题描述】:
我的页面上有一个简单的表单:
<form id="add_item_form" role="form">
<input type="text" name="newitem" value="" id="new-item-input"/>
<button type="button" id="new-item-button">go</button>
</form>
我有一些 JavaScript 用于捕获按钮单击或用户从文本输入中按 ENTER 键。这个想法是捕获 ENTER keyup 事件,然后以编程方式单击按钮。单击按钮时,应该发生一个 ajax 发布事件。这是 JavaScript:
$(function() {
console.log('start');
// give the focus to the text input
$("#new-item-input").focus();
// if the user hits enter in the text input, click the button
$("#new-item-input").keyup(function(event){
if(event.keyCode == 13){
$("#new-item-button").click();
}
});
// the callback function that is run if ajax succeeds
var new_item_ajax_success = function(result) {
console.log('success');
$("#new-item-input").focus();
}
// the function that is run when the button is clicked
var new_item_button_clicked = function() {
console.log('new item button clicked!');
$.post('/add_item/', {});
}
// add the function to the button
$('#new-item-button').click(new_item_button_clicked);
console.log('end');
});
我的期望是无论用户点击 ENTER 还是点击按钮,行为都应该是相同的。然而,事实并非如此。当用户按 ENTER 时,控制台日志如下:
new item button clicked!
start
end
另外,我的服务器日志记录了一个 GET 请求。我认为控制台日志中的start 和end 表示页面正在重新加载。
当用户点击按钮时,控制台日志如下:
new item button clicked!
POST http://localhost:8000/add_item/ 403 (FORBIDDEN)
另外,我的服务器日志记录了一个 POST 请求。 (预计会出现 403 错误。)
我的问题:为什么在这两种情况下我都没有得到预期的 POST 请求行为?
【问题讨论】:
-
您可以使用
key down或key press事件处理hitting 事件
标签: javascript jquery ajax forms post