Javascript 如何从javascript呈现部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2331130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to render a partial from javascript
提问by 99miles
I have a select that gets populated depending on the selection in a different select To do this, I did what is recommended in Railscast #88 on 'Dynamic Select Menus'.
我有一个选择,它根据不同选择中的选择进行填充。为此,我做了 Railscast #88 中关于“动态选择菜单”的建议。
But now I need to render a partial, passing in the value selected in each of those selects. I can't figure out how to simply trigger a method call from the :onchange event in the select, so I'm thinking I need to call render :partial from within the javascript handler that detects the selects change event. But I can't figure out how. I tried the following in the javascript method (in the .js.erb file) but it doesn't work as hoped:
但是现在我需要渲染一个部分,传递在每个选择中选择的值。我不知道如何简单地从选择中的 :onchange 事件触发方法调用,所以我想我需要从检测选择更改事件的 javascript 处理程序中调用 render :partial 。但我无法弄清楚如何。我在 javascript 方法中(在 .js.erb 文件中)尝试了以下内容,但没有按预期工作:
function staffSelected() {
$('date_area').show();
<% render :partial => "calendar" -%>
}
Anyone have a good solution?
有人有好的解决方案吗?
采纳答案by Mike Trpcic
You can't render a partial inside of JavaScript to detect change events. Ruby is server side, and JavaScript is client side. By the time your JavaScript runs, your Ruby has already been parsed into regular ol' HTML.
您无法在 JavaScript 内部呈现部分来检测更改事件。Ruby 是服务器端,JavaScript 是客户端。当您的 JavaScript 运行时,您的 Ruby 已经被解析为常规的 ol' HTML。
Your best bet is to do the following:
最好的办法是执行以下操作:
Use an AJAX control (there are Prototype/scriptaculous ones) to hit your server in the onchange event. Your server can send back RJS to update the other dropdowns, orit can return back standard JSON and you can populate the other dropdowns manually in the onSuccessmethod of the AJAX call.
使用 AJAX 控件(有 Prototype/scriptaculous 控件)在 onchange 事件中访问您的服务器。您的服务器可以发送回 RJS 以更新其他下拉列表,或者它可以返回标准 JSON,您可以onSuccess在 AJAX 调用的方法中手动填充其他下拉列表。
回答by miligraf
I think this is what you are looking for. I am rendering the partial within a DIV with "colors" ID, the partial is rendered only if the selected radio button's value is red:
我想这就是你要找的。我在带有“颜色”ID 的 DIV 中渲染部分,仅当所选单选按钮的值为红色时才会渲染部分:
<script language="javascript" type="text/javascript">
jQuery(function($){
$('#radio-buttons input[type=radio]').click(function() {
if ($(this).attr("value") === "red") {
$("#colors").html('#{escape_javascript(render :partial => "colors")}');
}
});
});
</script>

