如何将 Rails 变量传递给 AJAX 响应函数?
How to pass Rails variable to AJAX response function?
在AJAX我写:
$.ajax({
URL: '/new_avatar',
type: 'POST',
data: { username: 'alizade' },
success: function(response){
alert(response);
},
})
Route.rb:
post '/new_avatar' => 'avatars#new_avatar'
Avatar.rb 型号:
self.new_avatar(username)
Avatar.where(username: username).select('avatar').last
end
Avatars_Controller:
def new_avatar
@username = params[:username]
@result = Avatar.new_avatar(@username)
end
那么,如何将@result发送到AJAX响应函数并提醒数据库选择结果?
您需要在控制器方法中使用 render :text
def new_avatar
@username = params[:username]
@result = Avatar.new_avatar(@username)
render :text => "#{@username} has this result:- #{@result.inspect}"
end
假设您只需要此服务的响应,您可以使用以下方式获取结果。
def new_avatar
@username = params[:username]
render :json => Avatar.new_avatar(@username)
end
在AJAX我写:
$.ajax({
URL: '/new_avatar',
type: 'POST',
data: { username: 'alizade' },
success: function(response){
alert(response);
},
})
Route.rb:
post '/new_avatar' => 'avatars#new_avatar'
Avatar.rb 型号:
self.new_avatar(username)
Avatar.where(username: username).select('avatar').last
end
Avatars_Controller:
def new_avatar
@username = params[:username]
@result = Avatar.new_avatar(@username)
end
那么,如何将@result发送到AJAX响应函数并提醒数据库选择结果?
您需要在控制器方法中使用 render :text
def new_avatar
@username = params[:username]
@result = Avatar.new_avatar(@username)
render :text => "#{@username} has this result:- #{@result.inspect}"
end
假设您只需要此服务的响应,您可以使用以下方式获取结果。
def new_avatar
@username = params[:username]
render :json => Avatar.new_avatar(@username)
end