如何从javascript渲染部分 [英] How to render a partial from javascript

查看:93
本文介绍了如何从javascript渲染部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择,根据不同选择中的选择填充
为此,我做了'动态选择菜单'中Railscast#88推荐的内容。

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'.

但现在我需要渲染一个部分,传入每个选择中选择的值。
我无法弄清楚如何简单地从select中的:onchange事件触发方法调用,所以我想我需要在检测选择更改事件的javascript处理程序中调用render:partial。但我无法弄清楚如何。我在javascript方法中尝试了以下内容(在.js.erb文件中),但它没有按预期工作:

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:

function staffSelected() {
    $('date_area').show();
    <% render :partial => "calendar" -%>
}

任何人都有一个很好的解决方案吗?

Anyone have a good solution?

推荐答案

您无法在JavaScript中部分内部检测更改事件。 Ruby是服务器端,JavaScript是客户端。当您的JavaScript运行时,您的Ruby已经被解析为常规的'HTML。

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.

您最好的选择是执行以下操作:

Your best bet is to do the following:

使用AJAX控件(有Prototype / scriptaculous)在onchange事件中命中你的服务器。您的服务器可以发回RJS以更新其他下拉列表,它可以返回标准JSON,您可以在 onSuccess 中手动填充其他下拉列表AJAX调用的方法。

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, or it can return back standard JSON and you can populate the other dropdowns manually in the onSuccess method of the AJAX call.

这篇关于如何从javascript渲染部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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