如何在View文件夹中使用js文件 [英] How to use js file within view folder

查看:324
本文介绍了如何在View文件夹中使用js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails上使用ruby,我想在点击时呈现部分点击(使用jquery),例如:

I am using ruby on rails and I would like to render a partial on click (using jquery) an example of this being:

$('#submit').on('click', function(){  
  $('#lol').append("<%= escape_javascript(render :partial => 'myPartial' ) %>");
}

我基本上想提交一个表单,然后以只读格式显示结果(部分渲染),而无需刷新页面.问题是我不能在资产管道中使用渲染.如何从视图文件夹中包含我的JavaScript文件,或者什么是解决此问题的好方法?

I basically want to submit a form then show the results (render partial) after in a read only format without the page refreshing. Problem is I can't use render in the asset pipeline. How do I include my JavaScript file from the view folder or what would be a good solution for this issue?

推荐答案

查看您的代码

$('#submit').on('click', function(){  
 $('#lol').append("<%= escape_javascript(render :partial => 'myPartial' ) %>");
} 

我认为您在 ajax 和普通的 jquery 之间感到困惑.如果您不需要执行其他任何操作,则应使用普通的jquery来显示和隐藏您的内容.为此,您需要将此代码放入您的app/assets/javascript/application.js或创建一个新文件,然后在

I think you are confusing between ajax and normal jquery. If you don't need to perform anything else then you should use normal jquery to show and hide your content. For that you need to put this code in your app/assets/javascript/application.js or make a new file then require it inside application.js like

//= require file_name

在视图内部,可以通过以下方式隐藏内容的父元素:

Inside your view you can hide the parent element of your content by giving it a style like this:

#your_content_container{
  display: none;
}

然后将您的jquery代码放入your_file.js

Then place your jquery code in your_file.js

$(document).on("click","#submit",function(){
  $("##your_content_container").show();
})


如果它是您所要回答的形式,那么您还需要在控制器中执行一些逻辑,因此您应该使用 Ajax


If it's a form as your question says then you need to to perform some logic in your controller too so you should use Ajax

由于是表单,因此您需要在表单中使用 remote:true 选项,例如:

Since it's a form so you need to use remote: true option in your form something like:

<%= form_for(@user, remote: true) do |f| %>
  // your fields
<% end %>

然后可以在您的控制器内部

and then inside your controller you can have

def your_method
  #do your logic here
  respond_to do |format|
    format.js{}
  end
end

这将使Rails在视图中查找名为your_method.js.erb的文件,您可以在其中调用jquery并渲染部分文件.在your_method.js.erb

This will allow rails to look for a file named your_method.js.erb in your views where you can call your jquery and render your partial. In your_method.js.erb

$('#lol').append("<%=j render :partial => 'myPartial' %>");

有关详细信息,请参见 Working with Javascript in Rails

For details refer to Working with Javascript in Rails

这篇关于如何在View文件夹中使用js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆