按Enter键时用ajax发送数据 [英] send data with ajax when pressing enter

查看:77
本文介绍了按Enter键时用ajax发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的表格:

<form method="post">
    <input type="text" name="msg" id="chat_in" >
    <input type="button" name="bt" id="bt">
</form>

我想在用户按下回车或点击按钮时发送数据

i want to send data when user pressing enter or clicking on button

当用户点击按钮时它会起作用,但是当用户按下上的输入

it's work when user click on button , but it doesn't work when user pressing enter on chat_in

这里是我的javascript:

here is my javascript :

$(document).ready(function () {
    function SendData() {
        $.ajax({
            url: "save.php",
            type: "post",
            data: "msg="+$('#chat_in').val(),
            dataType: 'json', 
            success: function(){   
                alert("Sent");
            },
            error:function(){
                alert("failure");                
            }
        });
    }

    $('#chat_in').keypress(function(e) {
        if(e.which == 13) {
            alert('You pressed enter!');
            SendData();
        }
    });

    $('#bt').click(function() {
        SendData();
    });
});

我该如何解决这个问题?

how can i solve this problem ?

推荐答案

如果有人遇到同样的问题,只需删除表格并使用按钮

if anyone have same problem , just remove form and use button

在这种情况下你的html和javascript应该是这样的:

in this case your html and javascript should be something like this :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>final</title>
<script type="text/javascript" src="jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function() {
function SendData() {
   $.ajax({
        url: "save.php",
        type: "post",
        data: "msg="+$('#chat_in').val(),
        dataType: 'json', 
        success: function(){   
            alert("Sent");
        },


        error:function(){
            alert("failure");

        }
    });


}   



$('#chat_in').keypress(function(e) {
    if(e.keyCode == 13) {
        alert('You pressed enter!');
        SendData();
    }



    });


$('#bt').click(function() {
SendData();


 });





});

</script>
</head>

<body>
<input type="text" name="msg" id="chat_in" >
<input type="button" name="bt" id="bt">
</body>
</html>

这篇关于按Enter键时用ajax发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆