0

我在我的应用程序中使用jquery 文件上传实用程序。如果我通常在rails中有一些类似以下的代码......

if @course_module.save
  flash[:success] = "Class created!"
  redirect_to course_course_modules_path(@course)
else
  render 'new'
end

如果我的表单中有错误,它将显示错误消息,如果保存成功,它将重定向到另一个页面。但是当页面是通过jquery插件提交的时候就不是这样了。原因是它需要返回一个 json 对象....类似于

         format.json {  
          render ':json => [@course_module.to_jq_upload].to_json ' 
        }

我将如何代替返回 json,而是执行第一个代码片段?如果保存成功则通过重定向,或者如果不成功则显示错误消息?我试过类似下面的东西......

render 'new'

但这没有用。

4

1 回答 1

0

The normal ajax call has a success and error methods, just add to the json response a redirect_url key having the path you want to go to as the value and inside the success method redirect to this url.

$.ajax({
 type: "GET",
 url: '/path to your controller',
 datatype: 'json',
 success: function(data) {
   window.location.href = data.redirect_url
 };

});

and your json response should look like this inside the controller

render :json => {course_module: @course_module.to_jq_upload, redirect_url: course_course_modules_path(@course) }.to_json 

I hope that's what you are looking for

于 2012-10-21T09:16:09.563 回答