简体   繁体   English

如何在不提交表单的情况下使用ruby访问表单元素值?

[英]How do I access form element values using ruby without submitting the form?

Okay I have an extensive ruby application running behind Ruby on Rails right now. 好的,我现在有一个广泛的ruby应用程序在Ruby on Rails后面运行。 This application needs form input but I don't want to refresh the page when I update the text box. 该应用程序需要表单输入,但是我不想在更新文本框时刷新页面。 What I mean is: 我的意思是:

I have a form that has two text boxes, one is called "starttime" and one is called "endtime". 我有一个包含两个文本框的表单,一个被称为“开始时间”,一个被称为“结束时间”。 I somehow need to get the value of these text boxes (what a user has typed in) into ruby when a button is pressed. 我不知何故需要在按下按钮时将这些文本框(用户输入的内容)的值输入到ruby中。 Is there some sort of equivalent to javascript's document.form.starttime.value command but for ruby? 除了Ruby,是否有某种等效于javascript的document.form.starttime.value命令? Or is there some way to submit the form data, retrieve it, but not refresh the page such as using ajax? 还是有某种方法可以提交表单数据,检索它,但不刷新页面(例如使用Ajax)? I know ajax is used to manipulate the DOM dynamically without refreshing the page, but I really just need to retrieve data. 我知道ajax用于动态操作DOM而不刷新页面,但是我真的只需要检索数据。 Any help would be greatly appreciated, I simply cannot find this anywhere. 任何帮助将不胜感激,我根本找不到任何地方。

You can do this quite easily with jQuery . 您可以使用jQuery轻松完成此操作。 Give the start time and end time form elements a distinct ID (I use startDate and endDate below) and you can easily retrieve them, then send the data to a Rails action that can process them in the background and if necessary, update the DOM with any relevant data when you click on a button (below assumes an input button with the ID SendDateValues ). 给开始时间和结束时间表单元素一个独特的ID(我在下面使用startDateendDate ),您可以轻松地检索它们,然后将数据发送到可以在后台处理它们的Rails操作中,并在必要时使用DOM更新单击按钮时的任何相关数据(以下假设输入按钮的ID为SendDateValues )。

Something like this: (Not tested) 这样的事情:(未经测试)

<script type="text/javascript">
//<![CDATA[

$("#SendDateValues").click(function() {
  $.ajax({
    url: '/SomeController/ProcessDateData/",
    data: 'startDate=' + $("#startdate").val() + "&endDate=" + $("#endDate").val(),
    success: function(html) { //DO SOMETHING WITH THE RESULT },
    type: 'post'
  });
});

//]]>$
</script>

Play with the results... Use Firebug or something similar to check what gets passed. 玩转结果...使用Firebug或类似工具检查通过的内容。 Check your Rails event log to see what data your action gets. 检查您的Rails事件日志,以查看您的操作获取什么数据。

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

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