在 Ruby 中渲染普通 JavaScript 时出现问题
在我的控制器中,我尝试渲染普通 JavaScript,但得到了意外的结果。这是执行 post = DataFile.save(params[:upload]) 之前期望的代码
class UploadController < ApplicationController
def index
render :file => 'app\views\upload\uploadfile.rhtml'
end
def uploadFile
render :js => "alert('Hello Rails');"
post = DataFile.save(params[:upload])
end
end
,我应该看到一个警报框,但我看到一个下载框。可能是什么问题?
In My controller I am trying to render vanilla JavaScript but am getting an unexpected result. This is the code
class UploadController < ApplicationController
def index
render :file => 'app\views\upload\uploadfile.rhtml'
end
def uploadFile
render :js => "alert('Hello Rails');"
post = DataFile.save(params[:upload])
end
end
Am expecting before executing post = DataFile.save(params[:upload]) I should see a alertbox but I am seeing a download box. What could be the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
render :js
将发送 MIME 类型text/javascript
的数据浏览器将看到此内容并尝试下载或显示它(我的浏览器 Chromium 将 .js 文件显示为纯文本。)
render :js
实际上是返回一些将由 处理的 JavaScript代码已经在该页面上。本质上,您可以从 jQuery 进行 AJAX 调用:
这是从我的项目中获取的一些代码。这里,没有定义 dataType,因此 jQuery 会智能地“猜测”返回什么类型的数据。它发现它是 MIME-Type:
text/javascript
并执行它。如果我们使用您的代码,将导致显示警报对话框。本质上,您需要已经加载了一个页面,并且该页面必须等待“vanilla JavaScript”返回。
如果您只想为该特定操作执行一些代码,则只需在模板/视图中使用
javascript_tag
对其进行包装,或者包含外部 .js 文件。render :js
will send data with the MIME typetext/javascript
Browsers will see this and attempt to download or display it (my browser, Chromium, displays .js files as plaintext.)
render :js
is really meant to return some JavaScript that will be processed by code already on that page.In essence, you can have an AJAX call from jQuery:
This is some code taken from a project of mine. Here, no dataType is defined, so jQuery intelligently "guesses" what type of data is returned. It sees that it is MIME-Type:
text/javascript
and executes it. Which if we were to use your code, would result in an alert dialog being shown.In essence, you need to have a page already loaded, and the page has to be waiting for the "vanilla JavaScript" to be returned.
If you just want to execute some code for that particular action, you just have to wrap it using
javascript_tag
in your template/view, or include an external .js file.