简体   繁体   English

Rails AJAX部分,无需提交表单

[英]Rails AJAX partial without submitting form

I'd like to create a page where there are two columns: 我想创建一个包含两列的页面:

| | Form to create a pizza | 制作披萨的表格| Suggested Pizzas | 建议的披萨|

As you use the form on the left column to create your pizza, the column on the right starts suggesting different types of pizza you could order based on the left customization. 当您使用左侧列中的表单创建披萨时,右侧列开始建议您可以根据左侧自定义订购不同类型的披萨。

All of the tutorials I have found bind the reloading of the partial to the form submission, however, I'd like for the partial to reload every time an input blurs or a select is changed. 我发现的所有教程都将部分文档的重新加载绑定到表单提交,但是,我希望每次输入模糊或更改选择时都重新加载部分文档。

Is there an easy way to do this with Rails? 有没有简单的方法可以用Rails做到这一点?

I'd like to just grab the un-submitted @pizza object and send that to the partial every time a blur event occurs... 我只想抓住未提交的@pizza对象,并在每次发生模糊事件时将其发送给局部对象...

controller 调节器

def my_pizza
  @pizza = Pizza.all
  respond_to do |format|
    format.js
  end
end

view 视图

my_pizza.js.haml my_pizza.js.haml

$('#pizza').html('#{j render(partial: 'pizzas/piza', collection: @pizzs)}');

routes 路线

get 'pizza' => "pizza#my_pizza"

Inside the js file 在js文件中

$(document).on('change', 'input', function() {
  // you can create your ajax call which will call the my_pizza method in which action you want to call. 
});

You can add ajax and what ever event you want to call you can call it easily and when you will call the respective method it will updated the partial file respectively 您可以添加ajax,无论您要调用什么事件,都可以轻松调用它,当您调用相应的方法时,它将分别更新部分文件

I think you gave yourself the answer. 我想你给了自己答案。 Just attach an event listener to the keyup's on the form and submit via ajax. 只需将事件侦听器附加到表单上的keyup并通过ajax提交即可。

$('form').on('blur', function() {
  // submit ajax and do something with the response here
});

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

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