简体   繁体   English

一个请求后禁用AJAX提交按钮

[英]AJAX submit button disabling after one request

I'm building a Rails app and have a Javascript form using AJAX and JQUERY. 我正在构建一个Rails应用程序,并使用AJAX和JQUERY编写了Javascript表单。 The form is submitting correctly and the content is injecting into the DOM just fine but once this happens the submit button greys out and a new request cannot be submitted until I refresh the page. 表单可以正确提交,内容可以很好地注入到DOM中,但是一旦发生这种情况,提交按钮就会变灰,并且只有在刷新页面后才能提交新请求。

I compared the code to a previous app I built and it's identical. 我将代码与我之前构建的应用程序进行了比较,并且完全相同。 The only difference I can see is that the previous app was built with Rails '4.2.10' and this new one uses Rails '5.2.3' 我可以看到的唯一区别是,以前的应用程序是用Rails'4.2.10'构建的,而这个新应用程序使用的是Rails'5.2.3'

$('#new_order').on('submit', function(e) {
  $.post(this.action, $(this).serialize())
   .done(function(response) {
    let o = new Order(response)
    $('#order_address').val("")
    $('order_special_instructions').val("")
    $('#orders').append(o.format())
  }).error(function() {
    alert('error')
  })
  e.preventDefault()
})

In your case I think the problem is you use e.preventDefault() when you submit, but you didn't replace this form with new content. 在您的情况下,我认为问题在于您在提交时使用e.preventDefault() ,但没有用新内容替换此表单。 So this form will stay in submitting status. 因此,此表格将保持提交状态。

Since you are using Rails 5.2, I'll recommend to use form_with instead of jQuery ajax. 由于您使用的是Rails 5.2,因此我建议您使用form_with而不是jQuery ajax。 It's default as ajax request in Rails way and you just have to render partial you want in create.js.erb . 在Rails中,它默认为ajax请求,而您只需要在create.js.erb呈现所需的部分。

It will be something like this: 将会是这样的:

orders/_form.erb

<%= form_with model: Order.new, url: orders_path do |f| %>
<%= f.submit %>

And your create.js.erb 还有你的create.js.erb

let orderForm = "<%= j(render('orders/form')) >";
$('#new_order').html(orderForm);
$('#order_address').val("")
$('order_special_instructions').val("")

let order = "<%= j(render('orders/order')) >"
$('#orders').append(order)

And don't forget to include rails-ujs in your assets pipeline, or import it in case you use webpacker. 并且不要忘记在资产管道中包括rails-ujs,或者在使用webpacker的情况下将其导入。

Ok I figured it out. 好吧,我知道了。 Rails 5 automatically disables the submit button after submitting a request. 提交请求后,Rails 5自动禁用“提交”按钮。 I had to add 我必须添加

data: { disable_with: false } 数据:{disable_with:假}

to my submit button in my view. 转到我视图中的“提交”按钮。

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

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