我尝试使用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:
<form id="send-message-area" method="POST" action="sendchat.php">
<input type="text" name="from" id="from" value="<?php echo $me;?>" hidden>
<input type="text" name="to" id="to" value="<?php echo $other1;?>" hidden>
<input type="text" name="when" id="when" value="<?php echo $date;?>" hidden>
<textarea class="crazytext" name="msg" id="chatty"></textarea>
<input type="submit" name="chat" values="chat" class="crazytext2" hidden>
</form>
如果有必要,可以使用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);
}
});
}
});
});
答案 0 :(得分:4)
您需要阻止默认提交操作:
$('.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()
}
});
}
});