【问题标题】:Redirecting to another page via a json call通过 json 调用重定向到另一个页面
【发布时间】:2012-09-21 23:45:50
【问题描述】:

我在我的应用程序中使用jquery file upload 实用程序。如果我在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,而是执行第一个代码 sn-p?如果保存成功则通过重定向,或者如果不成功则显示错误消息?我已经尝试过类似以下的...

render 'new'

但这没有用。

【问题讨论】:

  • This might help。这是来自 Jquery 文件上传 github repo 的 Wiki 页面的示例。

标签: jquery ruby-on-rails ajax ruby-on-rails-3 json


【解决方案1】:

普通的 ajax 调用有一个成功和错误方法,只需在 json 响应中添加一个 redirect_url 键,该键具有您要转到的路径作为值,并在成功方法内重定向到此 url。

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

});

你的 json 响应在控制器内部应该是这样的

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

我希望这就是你要找的东西

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 2019-09-25
    • 2022-01-27
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 2016-12-14
    相关资源
    最近更新 更多