简体   繁体   English

使用Rails和JQuery提交表单时重新呈现JavaScript

[英]Re-render javascript when form is submitted using rails and jquery

I am a newbie developing using rails and jquery and having been searching everywhere for a simple example of how to do this for days. 我是一个使用Rails和jquery进行开发的新手,并且到处搜索了几天的简单示例。 I have a page, poweroutput.html.erb , that shows the power output of a customer's solar power system for a particular date. 我有一个页面poweroutput.html.erb ,它显示特定日期客户的太阳能系统的功率输出。 When they input a different date, I want them to see different output, but without having to reload the page. 当他们输入不同的日期时,我希望他们看到不同的输出,但不必重新加载页面。 On my page I have some javascript as well as a form (for submitting the date for which a user would like to see the power output) as follows: 在我的页面上,我有一些JavaScript以及一个表单(用于提交用户希望查看电源输出的日期),如下所示:

<head>
<script type="text/javascript">
    // a lot of javascript
</script>
</head>

<% form_tag(poweroutput_path, :method=>'post', :id => "date-form", :remote => true ) do %>
    <%= text_field_tag(
              'dt', nil,
              {  :id => 'date-field',
                 :class => 'dateformat-d-dt-m-dt-Y',
                 :value => Time.now.getlocal.strftime("%d.%m.%Y")            
              })
    %>
    <%= submit_tag "Go" %>
<% end %>

All I want is that the javascript on my page be re-rendered when the form is submitted. 我想要的是在提交表单后重新呈现页面上的javascript。 My page's controller action is currently as follows: 我页面的控制器操作当前如下:

def poweroutput      
  # some code 

  if request.xhr?
    @date = params[:dt]         # dt is posted when form is submitted
  else 
    @date = Time.now.getlocal.strftime("%d.%m.%Y")
  end

  respond_to do |format|
    format.html 
    format.js 
  end
end

All I want is for the javascript on my page to be re-rendered with a different @date when my form is submitted. 我想要的是在提交表单时使用不同的@date重新呈现页面上的javascript。 Does anyone know a simple way to do this? 有人知道这样做的简单方法吗?

If it is a lot of javascript, then: 如果有很多JavaScript,则:

  1. Put the date somewhere in the web page (vg, a hidden field) 将日期放在网页中的某处(vg,隐藏字段)
  2. Modify the javascript so it gets the value from there. 修改javascript,以便从那里获取值。
  3. Create a separated .js library for the JavaScript, and load it in the page. 为JavaScript创建一个单独的.js库,并将其加载到页面中。

That way the browser will profit from caching the javascript, reducing both the load in your server and download time for the page. 这样,浏览器将从缓存javascript中获利,从而减少服务器的负载和页面的下载时间。

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

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