新手问题 ruby render 用法

xiaoxiao · August 26, 2013 · Last by xiaoxiao replied at August 26, 2013 · 4526 hits

controller 代码如下 if File.file? file send_file file, :x_sendfile=>true else render :text => "the file does not exist" end 这样的话如果条件为 false,浏览器就显示 the file does not exit。 但是我想只跳出一个弹窗,把 render :text => "the file does not exist"改成 render :js => "alert('Hello Rails');" 但是执行后还是没跳出弹窗,而是显示 alert('Hello Rails');就好像 js 代码没执行一样。 什么问题。。。。求指教

你用 chrome dev tool 看看,你发的请求的 accept header,应该是'text/html'。所以浏览器不会将 rails 返回的字符串当成 js 处理。 要实现的话可以 render 一个 template,template 里面包含 js 代码,或者用 js 发起请求,请求指定是 script。

改成 ajax 请求发起 然后前端写 js 判断返回是否报错(无文件)然后弹窗 但是我建议你 不要弹窗 做一个漂亮的 404 File not find 的页面是上策

别这样做。

无效链接就给个 404 页面,自己程序生成的下载链接就应该是有效的。

我换了另一种方法试了

You need to Sign in before reply, if you don't have an account, please Sign up first.