[英]How to pass json response from controller to ajax call in rails
這是我在js文件中的ajax調用部分:
$("#sign_submit").click(function(){
email_id = $("#user_email").val();
password = $("#user_password").val();
data = {email: email_id, password: password };
url = user/sign_in';
$.ajax({
url: url,
data: data,
cache: false,
type: "post",
success: function(data){
console.log(data);
}
});
});
這是我的控制器動作:
def create
@user = User.find_by_email(params['email'])
if @user.nil?
respond_to do |format|
format.json {render :json => {:response => 'User is invalid'} } #how to pass json response here.
end
end
if @user.check_valid_user?(params['password'])
set_dashboard_location
set_current_user(session[:customer_id])
render js: %(window.location.href='#{session["spree_user_return_to"]}')
else
#redirect_to '/' and return
#how to psas json response here.
end
end
在創建動作(其他部分)中,我需要將有關(無效用戶/無效用戶憑據)的json響應傳遞給我的ajax調用,以便在查看頁面上提醒用戶。
我很難理解問題出在哪里,但我會盡力為您提供幫助。
從Rails控制器渲染JSON的基本命令是
render json: @user
例如。 我看到您在某個塊中寫了類似的內容。 當你寫
respond_to do |format|
format.json { render json: @foo }
end
僅當查詢的網址以.json(查詢的格式) url = user/sign_in.json
才會進行json呈現。因此,此處url = user/sign_in.json
將呈現json,但url = user/sign_in
將假定格式為html(默認值格式,您可以在路線定義中進行更改),並且不會呈現任何內容。
如果您需要渲染json,無論網址如何。 請勿將其放在respond_to
塊中。 如果是ajax調用或其他調用,如果需要兩種不同的行為,請使用url foo/bar.json
如果在rails根文件夾中運行rake routes
,則會看到類似/users/sign_in(.:format)
url,這意味着/users/sign_in.toto
會將:format
設置為toto
我希望這很清楚! 如果您希望在路線中設置默認格式,請執行以下操作:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.