简体   繁体   English

如何计算点击次数,然后发送带有该数字的 ajax 请求?

[英]How can I count the number of clicks and then send an ajax request with that number?

I have a button that I want to run a function that will make an ajax call and update click_count on my db.我有一个按钮,我想运行一个 function 来调用 ajax 并更新我的数据库上的 click_count。

$.ajax({
        url: 'my_url'
        type: 'post',
        data: {id: 1},
        success: function(response){
            console.log(response.click_count);
        }
    });

Now, I want to simplify ajax call when user click button quickly.现在,当用户快速单击按钮时,我想简化 ajax 调用。 For example, if user click the button 10 times quickly, i will send request with param like:例如,如果用户快速单击按钮 10 次,我将发送带有如下参数的请求:

$.ajax({
        url: 'my_url'
        type: 'post',
        data: {id: 1, click_count:10}, // click_count=10;
        success: function(response){
            console.log(response.click_count);
        }
    });

So I just send 1 ajax request for 10 clicks instead of 10 requests.所以我只发送 1 个 ajax 请求,点击 10 次,而不是 10 次请求。

There are some libs for that, but this will work with vanilla js.有一些库,但这将适用于 vanilla js。

var click_count = 0;
var click_timeout;
function countIt() {
   if( click_timeout ) {
       clearTimeout( click_timeout );
   }
   click_count ++;
   click_timeout = setTimeout( function() {
       $.ajax({
            url: 'my_url'
            type: 'post',
            data: {id: 1, click_count:click_count},;
            success: function(response){
                console.log(response.click_count);
            }
        });
       click_count = 0;
   }, 1000 ); // 1 Second for next click
}

You can work with a timeout and send the request after the user stopped clicking for a specific time.您可以使用超时并在用户停止单击特定时间后发送请求。

  1. Define a variable outside: var timeout = null;在外面定义一个变量: var timeout = null;
  2. Use this code within you click handler (you can play around with the 500ms):在单击处理程序中使用此代码(您可以使用 500 毫秒):
clearTimeout(timeout);

timeout = setTimeout(function () {
    $.ajax({
        url: 'my_url'
        type: 'post',
        data: {id: 1, click_count:10}, // click_count=10;
        success: function(response){
            console.log(response.click_count);
        }
    });
}, 500);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM