尝试在文本框上提交表单输入按下jquery ajax不起作用
我正在尝试使用jquery和ajax提交表单,但它失败了。 这是代码:
$(document).ready(function () { $('.crazytext').keydown(function (event) { if (event.keyCode == 13) { $.ajax( { url: '/sendchat.php', type: 'POST', data: { 'from': $('#from').val(), 'to': $('#to').val(), 'when': $('#when').val(), 'msg': $('#chatty').val() } }); } }); });
这很简单,我想在输入按下后提交表单并将数据发送到sendchat.php而不重新加载页面。 这是html:
如有必要,sendchat.php的php代码
$fromuser = $_POST['from']; $touser = $_POST['to']; $when = $_POST['when']; $msg = $_POST['msg']; $seen = 0; $addchat = $db->prepare("INSERT INTO scorp_chats (Fromuser, Touser, Messagetime, Message, Seen) VALUES (:fromuser, :touser, :messagetime, :message, :seen)"); $addchat->execute(array(':fromuser' => $fromuser, ':touser' => $touser, ':messagetime' => $when, ':message' => $msg, ':seen' => $seen));
这是真的,它非常简单但却失败了。 如果我完全删除ajax部分,它可以工作,但我被重定向到页面,这不应该发生。
解决方案(感谢Barmar):
$(document).ready(function () { $('.crazytext').keydown(function (event) { // your input(textarea) class if (event.keyCode == 13) { event.preventDefault(); $.ajax({ url: 'sendchat.php', // script to process data type: 'POST', data: $("#send-message-area").serialize(), // form ID success: function(result) { $("#result").text(result); } }); } }); });
您需要阻止默认提交操作:
$('.crazytext').keydown(function (event) { if (event.keyCode == 13) { event.preventDefault(); // <---- $.ajax( { url: '/sendchat.php', type: 'POST', data: { 'from': $('#from').val(), 'to': $('#to').val(), 'when': $('#when').val(), 'msg': $('#chatty').val() } }); } });
DEMO