简体   繁体   English

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

[英]Render multiple params from rails controller with jquery/ajax request

Hey so I am new to Ajax but trying to get my head around this. 嘿,所以我是Ajax的新手,但是想尽一切办法。 The below code works and allows me to update the text in my view with Jquery. 下面的代码有效,并允许我使用Jquery更新视图中的文本。 I want to be able to do this twice but can't figure out how to define more params in the ajax request. 我希望能够两次执行此操作,但无法弄清楚如何在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 with data which is passed from my controller below: 我能够使用下面的控制器传递的data成功更新$('.current_user_thanks span').text

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? 例如data.user_namedata.user_email例如? Would I have to use Json? 我需要使用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! 谢谢!

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! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM