【问题标题】:Why Ajax does not work when you press enter [duplicate]为什么按回车键时Ajax不起作用[重复]
【发布时间】:2020-08-02 07:45:02
【问题描述】:

我有一个表单,我用 Ajax 发布了 POST,一切都很漂亮。但是当我按下回车键时,url 是 get 并且 ajax 不起作用。我希望 Ajax 在您按 Enter 时工作,我的代码:

function ajax2(){
	$.ajax({
		type:"POST",
		url:"ajax/alock.php",
		data:$("#formlock").serialize(),
		success:function(e){
			$("#result").html(e);
		}
	});
}

$("#btnlock").click(function(){
	ajax2();
});

/*I want Ajax to work when you press enter */
$("#formlock input").keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        ajax2();
    }
});
<form role="form" class="form-inline" id="formlock">
    <div class="form-group col-lg-12">
       <input type="password" placeholder="Şifre" name="pass" class="form-control lock-input">
         <button class="btn btn-lock" type="button" id="btnlock">
               <i class="fa fa-arrow-right"></i>
          </button>
     </div>
</form>

【问题讨论】:

标签: javascript php jquery ajax


【解决方案1】:

使用 jQuery 3.4.1 测试 jsFiddle,

您的代码运行良好...检查您的 jQuery 包含

或兼容性:https://www.quirksmode.org/dom/events/keys.html

https://jsfiddle.net/c1vruLhp/

<form role="form" class="form-inline" id="formlock">
    <div class="form-group col-lg-12">
       <input type="password" placeholder="Şifre" name="pass" class="form-control lock-input">
         <button class="btn btn-lock" type="button" id="btnlock">
               <i class="fa fa-arrow-right"></i>
          </button>
     </div>
</form>


    <script>
        function launch() {
            alert('you press enter');
        }

        $("#formlock input").keypress(function(event){
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if(keycode == '13'){
               launch();
            }
        });
    </script>

【讨论】:

    【解决方案2】:

    您需要在文件中包含 ajax 库

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    

    【讨论】:

    • OP 确实说他们可以在点击时发送它,所以他们一定已经包含了它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 2014-01-18
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多