반응형
Rails 3 : Ajax 호출에서 "redirect_to"하는 방법?
다음 attempt_login
메소드는 로그인 양식을 제출 한 후 Ajax를 사용하여 호출됩니다.
class AccessController < ApplicationController
[...]
def attempt_login
authorized_user = User.authenticate(params[:username], params[:password])
if authorized_user
session[:user_id] = authorized_user.id
session[:username] = authorized_user.username
flash[:notice] = "Hello #{authorized_user.name}."
redirect_to(:controller => 'jobs', :action => 'index')
else
[...]
end
end
end
문제는 redirect_to
작동하지 않는다는 것입니다.
이 문제를 어떻게 해결 하시겠습니까?
마지막으로
redirect_to(:controller => 'jobs', :action => 'index')
이것으로 :
render :js => "window.location = '/jobs/index'"
잘 작동합니다!
다음 요청을 위해 플래시를 유지하는 매우 쉬운 방법이 있습니다. 컨트롤러에서 다음과 같이하십시오.
flash[:notice] = 'Your work was awesome! A unicorn is born!'
flash.keep(:notice)
render js: "window.location = '#{root_path}'"
는 flash.keep
반드시 플래시가 다음 요청을 유지하게됩니다. 따라서이 root_path
렌더링되면 주어진 플래시 메시지가 표시됩니다. Rails는 굉장합니다 :)
나는 이것이 약간 더 좋다고 생각합니다.
render js: "window.location.pathname='#{jobs_path}'"
내 앱 중 하나에서 JSON을 사용하여 리디렉션 및 플래시 메시지 데이터를 수행합니다. 다음과 같이 보일 것입니다.
class AccessController < ApplicationController
...
def attempt_login
...
if authorized_user
if request.xhr?
render :json => {
:location => url_for(:controller => 'jobs', :action => 'index'),
:flash => {:notice => "Hello #{authorized_user.name}."}
}
else
redirect_to(:controller => 'jobs', :action => 'index')
end
else
# Render login screen with 422 error code
render :login, :status => :unprocessable_entity
end
end
end
그리고 간단한 jQuery 예제는 다음과 같습니다.
$.ajax({
...
type: 'json',
success: functon(data) {
data = $.parseJSON(data);
if (data.location) {
window.location.href = data.location;
}
if (data.flash && data.flash.notice) {
// Maybe display flash message, etc.
}
},
error: function() {
// If login fails, sending 422 error code sends you here.
}
})
모든 답변 중 최고를 결합 :
...
if request.xhr?
flash[:notice] = "Hello #{authorized_user.name}."
flash.keep(:notice) # Keep flash notice around for the redirect.
render :js => "window.location = #{jobs_path.to_json}"
else
...
def redirect_to(options = {}, response_status = {})
super(options, response_status)
if request.xhr?
# empty to prevent render duplication exception
self.status = nil
self.response_body = nil
path = location
self.location = nil
render :js => "window.location = #{path.to_json}"
end
end
컨트롤러 동작을 수정하고 싶지 않았기 때문에이 해킹을 생각해 냈습니다.
class ApplicationController < ActionController::Base
def redirect_to options = {}, response_status = {}
super
if request.xhr?
self.status = 200
self.response_body = "<html><body><script>window.location.replace('#{location}')</script></body></html>"
end
end
end
참고URL : https://stackoverflow.com/questions/5454806/rails-3-how-to-redirect-to-in-ajax-call
반응형
'developer tip' 카테고리의 다른 글
Eclipse Juno / Kepler / Luna CDT에서 C ++ 11을 활성화하는 방법은 무엇입니까? (0) | 2020.09.15 |
---|---|
Android Studio를 사용한 디버깅이 "Waiting For Debugger"에서 영원히 멈춤 (0) | 2020.09.15 |
노드 목록에 forEach가없는 이유는 무엇입니까? (0) | 2020.09.15 |
AJAX MVC를 통해 Excel 파일 다운로드 (0) | 2020.09.15 |
CSS를 통한 자동 완성 비활성화 (0) | 2020.09.15 |