ajax调用重定向到页面

时间:2016-07-04 11:11:45

标签: ruby-on-rails ajax

在我的服务器终端中,我看到Started GET“/ another”,但浏览器不会重定向到网址。这段代码有什么问题?

路线:

match '/example_url', to: 'controllerx#sup', via: 'get'

客户方:

$.ajax({
  type: "GET",// GET in place of POST
  contentType: "application/json; charset=utf-8",
  url: "/example_url",
  data : {example: 'hey'},
  success: function(result) {
    //TODO
  },
  error: errorFunction
});

控制器:

def sup
  respond_to do |format|
    format.js { redirect_to another_path }
  end
end  

1 个答案:

答案 0 :(得分:2)

您无法从控制器操作重定向,因为远程调用了操作。 试试这个:

客户端:

$.ajax({
  type: "GET",// GET in place of POST
  dataType: "json",
  url: "/example_url",
  headers: {
      'Content-Type': 'application/json'
  },
  data : {example: 'hey'},
  success: function(result) {
    window.location = result.location;
  },
  error: errorFunction
});

控制器:

def sup
  respond_to do |format|
    format.json { render json: { location: another_path } }
   end
end