簡體   English   中英

Rails-使用jQuery填充表單

[英]Rails - Using jQuery to populate a form

在我的頁面上我有以下內容:

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

給附加文件不是一個常見的用例,我不希望attach-file-form元素在加載時出現,它會減慢一切。

我想要發生的是用戶單擊“附加文件”,jQuery AJAX GET獲取表單並將其注入attach-file-form。

Rails正確的方法是什么?

在jQuery我有:

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

這聽起來不錯嗎?

在頁面上顯示文件上載表單但隱藏對您網站的性能幾乎沒有影響。 我建議將文件上傳表單默認為隱藏,並在單擊按鈕時觸發表單顯示。

然后你的JQuery代碼可以像下面這樣簡單:

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

如果你確實需要從服務器獲取它,你可以使用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