使用jquery / ajax请求从rails控制器渲染多个参数

时间:2022-11-26 21:59:09

Hey so I am new to Ajax but trying to get my head around this. The below code works and allows me to update the text in my view with Jquery. I want to be able to do this twice but can't figure out how to define more params in the ajax request.

嘿所以我是阿贾克斯的新手,但是试图了解这个问题。下面的代码工作,并允许我使用Jquery更新视图中的文本。我希望能够做到这两次,但无法弄清楚如何在ajax请求中定义更多参数。

My ajax function fires perfectly well on click.

我的ajax功能在点击时非常好。

$.ajax({
url: '/check-existing-user?email=' + user_email,
type: 'get',
dataType: 'html',
processData: false,
success: function(data) {
    if (data == "nil") {
        alert('No existing user');
    }
    else {
        $('form#new_user').submit();
        $('.current_user_thanks span').text(data);
    }
}
});

I am able to successfully update $('.current_user_thanks span').text withdata which is passed from my controller below:

我能够成功更新$('。current_user_thanks span')。text withdata,它从我的控制器传递到下面:

def check_existing_user
  @user = User.find_by_email(params[:email])
  if @user.present?
      if @user.confirmed?
          render :text => @user.first_name,
      else
          render :text => "nil"
      end
  else
      render :text => "nil"
  end
end

Is there any way I can pass multiple variables within data? Such as data.user_name and data.user_email for example? Would I have to use Json? and if so how as I have looked at plenty of examples and the above code is all I can get to work. Thanks!

有什么办法可以在数据中传递多个变量吗?例如data.user_name和data.user_email?我必须使用Json吗?如果是这样,我怎么看了很多例子,上面的代码就是我可以开始工作的。谢谢!

1 个解决方案

#1


2  

Try sending the whole object in json format

尝试以json格式发送整个对象

render :json => @user

or, do this

或者,这样做

json_data = { username: @user.username, email: @user.email, ... }
render :json => json_data

Hope that helps!

希望有所帮助!

#1


2  

Try sending the whole object in json format

尝试以json格式发送整个对象

render :json => @user

or, do this

或者,这样做

json_data = { username: @user.username, email: @user.email, ... }
render :json => json_data

Hope that helps!

希望有所帮助!