[英]Jquery: Ajax call is not working
I'm using Jquery to count the clicks and keypresses by the users. 我正在使用Jquery计算用户的点击次数和按键次数。
$(document).ready(function(){
var countClick = 0;
var keyClick = 0;
$("body").mousedown(function(){
countClick ++;
});
$("body").keypress(function(){
keyClick ++;
});
$("body").bind('keyup', function(e) {
if(e.keyCode >= 37 && e.keyCode <= 40){
keyClick ++;
}
});
});
Now, I want to send this to another page to save these data, when the user click in send button, but I presume the ajax call is not working and it's very simple. 现在,当用户单击“发送”按钮时,我想将其发送到另一页以保存这些数据,但是我认为ajax调用无法正常工作,并且非常简单。
$('#send').click(function(){
$.ajax({
type: 'post',
data: {mouse: countClick, teclado: keyClick},
url: 'save.php',
dataType: "json",
success: function(data){
alert(data);
},
error: function (e) {
console.log(e);
}
});
});
But none alerts and console log is being shown. 但是没有警报和控制台日志显示。 Do I need to "close" a form between button tag and specify
method
and action
? 我是否需要“关闭”按钮标签之间的表单并指定
method
和action
?
<form method="POST" action="#">
<button id="send"> Send Data </button>
</form>
Or that's not a rule, I don't need a form to make ajax call and send the data?! 还是这不是规则,我不需要表格来进行ajax调用并发送数据吗?
You do not necessarily need a form for an ajax call. 您不一定需要表单来进行Ajax调用。
Your counter variables do not have scope within the $("#send").click method, they are undefined outside document.ready method 您的计数器变量在$(“#send”)。click方法内没有作用域,它们在document.ready方法之外是未定义的
Since you're using Ajax to post, you need to prevent form from submitting automatically when clicking on send button. 由于您使用的是Ajax发布功能,因此您需要在单击“发送”按钮时阻止表单自动提交。 Since you didn't use button type="button", it defaulted to button type ="submit".
由于您未使用按钮类型=“按钮”,因此默认情况下将其设置为按钮类型=“提交”。
Here's the solution that works 这是有效的解决方案
var countClick = 0; var keyClick = 0; $(document).ready(function(){ $("body").mousedown(function(){ countClick ++; }); $("body").keypress(function(){ keyClick ++; }); $("body").bind('keyup', function(e) { if(e.keyCode >= 37 && e.keyCode <= 40){ keyClick ++; } }); }); $('#send').click(function(event){ $.ajax({ type: 'post', data: {mouse: countClick, teclado: keyClick}, url: 'save.php', dataType: "json", success: function(data){ alert(data); }, error: function (e) { console.log(e); } }); event.preventDefault(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="POST" action="#"> <button id="send" type="button"> Send Data </button> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.