简体   繁体   English

第n次单击后禁用AJAX按钮

[英]Disable AJAX button after nth click

Given I have a model Post which can have up to n Comments (the number is controlled by the Backend) and I have a view which allows to add a Comment via a AJAX request. 给定我有一个模型Post ,它最多可以包含n条 Comments (数字由后端控制),并且我有一个视图,该视图允许通过AJAX请求添加Comment What is the best way to tell the view upon the nth request to disable the Add-Comment-Form? 告诉第n个禁用添加注释表单的请求的最佳方法是什么?

The nth request is successfull so status code should still be 200/201 but the backend already "knows" that the nth + 1 call will invalidate the Post , so i want to somehow tell this to the view so it can take action before the user experiences the (catched) error upon nth + 1 submit. 第n个请求成功执行,因此状态代码仍应为200/201,但是后端已经“知道” 第n + 1个调用将使Post无效,因此我想以某种方式告诉视图,以便它可以在用户之前采取措施在第n + 1次提交时遇到了(捕获的)错误。

By now the backend renders html which is then simply attached to a div in the DOM, with JSON I might add an additional field but then would move the templating to the view again. 现在,后端呈现html,然后将其简单地附加到DOM中的div,使用JSON,我可能会添加一个附加字段,但随后会将模板再次移动到视图。

If someone has an idea for an elegant solution? 如果有人有一个优雅的解决方案的主意?

Just hide the "Add comment" button by JavaScript, when it will be "nth + 1". 只需通过JavaScript隐藏“添加评论”按钮,当它为“ nth + 1”时即可。 Or remove eventListener from button and change caption to smth like "You reached max comments". 或从按钮中删除eventListener,然后将标题更改为smth,例如“您已达到最大评论数”。

Keep a track of the number of clicks. 跟踪点击次数。 After the n th click, you can change the disabled attribute of your button to true . n次点击后,您可以将按钮的disabled属性更改为true

$(".myButton").attr("disabled",true);

Try having your server render javascript value for comment count and max comments. 尝试让您的服务器呈现javascript值,以获取评论数和最大评论数。 Then you can increment the count value in your success function as well as perhaps render the html comment. 然后,您可以在成功函数中增加计数值,也可以呈现html注释。

Something like 就像是

 var commentCount = *value from server*;
 var maxComments =*value from server*;

 $('#mybutton').click(function(){
     $.ajax({
             // your code here 
     })
    . success(function (response) {
             // process response
             commentCount ++;
             if( commentCount >= maxComments) 
                  $('#mybutton). prop('disabled', true);
     });

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

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