Rails:使用下拉菜单中的输入而不发布
总的来说,我对 Rails 和 Web 开发还很陌生。我需要显示两个下拉菜单,州和学校,这样学校仅在用户选择州后才显示,并且学校应仅显示所选州的学校。我不知道的是如何使用州选择来动态决定要显示哪些学校,而用户不必单击“提交”。我知道我可能需要使用 JavaScript,但不太了解 JS,我不太确定该怎么做。希望我说得有道理。谢谢!
I'm pretty new to Rails and web dev in general. I need to display two dropdown menus, states and schools, such that schools is only displayed after the user has chosen the state, and schools should only display the schools in the chosen state. What I don't know is how I can use the states choice to decide dynamically what schools to display, without the user having to click Submit. I understand that I may need to use JavaScript, but not knowing JS well, I'm not really sure how to do that. Hope I'm making sense. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
下面是一个简单示例,根据 JavaScript 中已有的数据结构动态填充选择。如果您需要在用户选择一个州并返回学校列表后执行服务器请求,您将需要不同的代码(并且需要一个像 jQuery 这样的库)。
Here is a simple example of dynamically populating a select based on data structures already in your JavaScript. If you need to perform a server request after the user selects a state and return the list of schools, you'll need different code (and helpfully a library like jQuery).
我想你想用 AJAX 来做到这一点。我不会为 Rails 1 定制这个,但你应该能够遵循这个想法。您的第一个下拉列表有一个州列表,每个州都有一个学校列表。
所以也许你没有 jQuery,也许在 Rails 1 中渲染 json 是不同的......但想法是相同的。您在状态下拉列表中附加了一些 javascript,以便当状态发生变化时,您可以提取该状态的 id 并对控制器进行 AJAX 调用。该 AJAX 调用的最后一个参数是一个 success 函数,它循环访问控制器发回的所有学校,清除学校下拉列表,并将选项一一添加到下拉列表中。
I think you want to do this with AJAX. I'm not going to customize this for Rails 1 but you should be able to follow the idea. Your first dropdown has a list of states, and each state has a list of schools.
So maybe you don't have jQuery and maybe rendering json is different in Rails 1... but the idea is the same. You have some javascript attached to your states dropdown so that when it changes, you pull off the id of that state and make an AJAX call to your controller. The last parameter to that AJAX call is a success function that loops through all the schools sent back by the controller, clears the schools dropdown, and adds options into the dropdown one by one.