如何记录按键持续时间并在jquery中将数据发送到服务器

时间:2016-09-11 15:54:00

标签: jquery mobile

我正在尝试设计一个移动小程序,用于衡量用户按下按钮并将其发送回服务器进行记录的时间。小程序将记录服务器的IP,时间GMT和按键持续时间。此信息将附加到csv文件。

1 个答案:

答案 0 :(得分:0)

我认为标题应该是按下按钮持续时间。您可以使用jquery mouseup 鼠标按下事件方法在浏览器中获取按钮按下的持续时间。在移动应用中你可以用 touchstart 替换mousedown,用 touchend 替换mouseup。我已经创建了一个工作小提示来演示它。

Click here to see working fiddle

HTML

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
 <input type="button" id="testButtonPressDuration" value="Press"/>   

的Javascript

 $(document).ready(function(){
    var date1;
    var date2;

    $("#testButtonPressDuration").on('mousedown touchstart',function(){       
            date1=new Date();
    });
     $("#testButtonPressDuration").on('mouseup touchend',function(){       
        date2=new Date();
        var milliseconds=date2.getTime()-date1.getTime();
        alert("Button pressed for "+milliseconds+" milliseconds");

        //send the button pressed duration to server
        sendDataToServer(milliseconds);

    });

});

function sendDataToServer(keyPressedDuration)
{

         //full path to your server action processing the request
         var url="http://somedomain/someproject/someaction.php";
         $.ajax({
            url: url,
            method: "POST",
            dataType: "json",//enable CORS in server
            data: {keyPressedDuration:keyPressedDuration},
            success: function (result) {

               //handle succesful data send from server

            },
            error: function (jqXHR, textStatus, errorThrown)
            {
              //handle errors
            }
        });

}