简体   繁体   English

如何在Rails中执行控制器返回的JavaScript?

[英]How to execute a javascript returned by controller in Rails?

I want to upload an image and show it without refresh. 我想上传图像并显示而不刷新。

The method I know is to use an hidden iframe and set the target of the form to it. 我知道的方法是使用隐藏的iframe并将表单的目标设置为其。

Then return a piece of javascript from controller calling "parent.func()" to do something... 然后从调用“ parent.func()”的控制器返回一段javascript以做某事...

But here is my problem: 但是这是我的问题:

It seems that the javascript will not be executed unless the foreground knows the dataType is "script", something like: 除非前台知道dataType为“ script”,否则似乎不会执行javascript,例如:

$.ajax {
    dataType:"script"
}

but when submit the form, I have to use 但是当提交表格时,我必须使用

$("...").submit()

So I cannot specify the dataType.... 所以我无法指定dataType。

Can anyone tell me what to do?... 谁能告诉我该怎么办?...

Or can you tell me another way to achieve my goal: 或者您可以告诉我另一种实现目标的方法:

upload a image and show it without refresh in Rails 3.2.0.. 上传图像并在Rails 3.2.0中显示它而无需刷新。

我认为您问题的正确答案是以下使用代码

render :inline => '<script type="text/javascript">parent.callback(data)</script>'

try to use remotipart gem: 尝试使用remotipart宝石:

http://github.com/JangoSteve/remotipart http://github.com/JangoSteve/remotipart

The way I have done it is the calling code (that calls $("...").submit() ) will listen for the load event on the hidden iframe, and then react; 我这样做的方法是调用代码(调用$("...").submit() )将侦听隐藏的iframe上的load事件,然后做出反应; rather than the server returning JavaScript that automatically runs. 而不是服务器返回自动运行的JavaScript。

On the iframe load event, you can turn the response into a JavaScript object if you are returning JSON: 在iframe加载事件中,如果您要返回JSON,则可以将响应转换为JavaScript对象:

// assuming you have a DOM element with a variable of "iframe"
var doc = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document;
var response = eval("(" + doc.body.innerHTML + ")");

Or, in your case if the response is just the image, then your load callback could put the response into a <div> or some other element you have already created on the page. 或者,如果您的响应只是图像,那么您的加载回调可以将响应放入<div>或您已在页面上创建的其他元素中。

You may want to check out the following plugin: https://github.com/valums/ajax-upload 您可能要检查以下插件: https : //github.com/valums/ajax-upload

Or, if you want to take advantage of HTML5 features, a more advanced plugin: https://github.com/valums/file-uploader 或者,如果您想利用HTML5功能,可以使用一个更高级的插件: https : //github.com/valums/file-uploader

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

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