为什么当您按Enter键时Ajax无法正常工作

时间:2020-04-19 21:17:44

标签: javascript php jquery ajax

我有一个表单,我用Ajax发布了POST,一切都很漂亮。但是当我按Enter键时,URL是get并且ajax无法正常工作。当您按Enter时,我希望Ajax运行,我的代码:

enter image description here

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>

2 个答案:

答案 0 :(得分:0)

您需要在文件中包含ajax库

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

答案 1 :(得分:0)

使用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>