简体   繁体   English

Rails-使用jQuery填充表单

[英]Rails - Using jQuery to populate a form

on my page I have the following: 在我的页面上我有以下内容:

<span id="attach-file" class="link">Attach a file</span>
  <div id="attach-file-form">
</div>

Give that attaching a file is not a common use case, I don't want the attach-file-form elements to be present on load, it would slow everything down. 给附加文件不是一个常见的用例,我不希望attach-file-form元素在加载时出现,它会减慢一切。

What I would like to happen is the user clicks "Attach a file", jQuery AJAX GET to get the form and inject it inside of attach-file-form. 我想要发生的是用户单击“附加文件”,jQuery AJAX GET获取表单并将其注入attach-file-form。

What's the right way in Rails to go about this? Rails正确的方法是什么?

in jQuery I have: 在jQuery我有:

$("#attach-file").live("click", function() {
    DO A GET TO A custom Method in the Attachment Controller
    Inject inside the div
});

Does this sound right? 这听起来不错吗?

Having the file upload form present on the page but hidden will have pretty much zero impact on the performance of your site. 在页面上显示文件上载表单但隐藏对您网站的性能几乎没有影响。 I'd recommend just defaulting the file upload form to hidden, and triggering display of the form when your button is clicked. 我建议将文件上传表单默认为隐藏,并在单击按钮时触发表单显示。

Then your JQuery code can be as simple as: 然后你的JQuery代码可以像下面这样简单:

$("#attach-file").live("click", function() {
  $("#file_upload_form").show();
});

If you do need to get this from the server, you can use the jQuery.get method to make a call to a Rails controller, which can output the form for you: 如果你确实需要从服务器获取它,你可以使用jQuery.get方法调用Rails控制器,它可以为你输出表单:

$("#attach-file").live("click", function() {
  $.get("/controller/action", function(html) {
    $("#file_upload_form").html(html);
  }
});

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

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