douduoyan5943 2019-07-12 14:09
浏览 134
已采纳

JQuery和PHP按Enter键进行处理

I have the following two files request.php and response.php. I used to send the request using a button

    <input type="button" value="Request message" onclick="post()"/>

but now I and considering using just the "Enter"(13) key.

The code works, however it shows the result just for a couple of milliseconds. In theory keydown function is working and getting the result from response, bt I dont know why just for a very short time.

Any tips?

request.php

<script type="text/javascript">

function post(){
$("#message").keydown(function (e) {
    if (e.keyCode == 13) {
    var message=document.getElementById("message").value;
    $.post('response.php',{postmessage:message},
    function(data){
    var result = $('#post_message').html(data);
    console
return result; });
    }
});
}
</script>

<form>
Enter Message:<input type="text" id="message" name="message" onclick="post()"/><br/>
</form>
<div id="post_message"></div>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

response.php

<?php
 function returnString() {
    $post_msg = $_POST['postmessage'];
    echo "Message entered ->", $post_msg ," <- here";
}
returnString();
?>
  • 写回答

3条回答 默认 最新

  • duanou1904 2019-07-12 14:27
    关注

    You are trying to mimic behavior that is already available by default with a form that only has one input.

    Thus your form is submitting and reloading the page.

    You don't need to listen to key event on the <input>. Just listen for the submit event of the form and prevent the default submit process

    $('form').submit(function(e){
        e.preventDefault();    
        var msg = $('#message').val();
    
        mockPost(msg).then(function(res){        
          $('#post_message').append('<p>' + res + '<p>')
        });    
    
    })
    
    
    function mockPost(v){
       return new Promise(function(resolve){
            setTimeout(function(){
              resolve('Message= ' + v)
            }, 200)
       })
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form>
    Enter Message:<input type="text" id="message" name="message"/><br/>
    </form>
    <div id="post_message"></div>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R