如何从返回的jQuery Ajax数据中获取Rails变量?

时间:2022-10-31 22:23:52

I have an Ajax request from a page in my Rails app that looks like so:

我在我的Rails应用程序中的页面中有一个Ajax请求,如下所示:

$.ajax({
 type: 'POST',
 url: '/users/create/',
 data: "screen_name=<%=@user.screen_name%>",
 success: createSuccessHandler,
 error: createErrorHandler,
 complete: hideLoadingImage
});

And currently the action responds with this:

目前,该行动的回应是:

respond_to do |format|
  format.js  { render :text => @user}
  format.html { redirect_to @user }
end

The create action works fine but how to I get the returned values (data) in my success method so I can do something like this?

create动作工作正常,但是如何在成功方法中获取返回值(数据),这样我可以做这样的事情?

function createSuccessHandler(data) {

    $("#div1").append(data.value1); 
    $("#div2").append(data.value2); 

}

Basically I'm trying to split the data up into different variables.

基本上我正在尝试将数据拆分为不同的变量。

1 个解决方案

#1


4  

Return json in your controller (e.g., add a format.json stanza and request that instead of the .js one). Then in your createSuccessHandler function you'll do something like:

在你的控制器中返回json(例如,添加一个format.json节并请求而不是.js节)。然后在您的createSuccessHandler函数中,您将执行以下操作:

var foo = eval(data);
$("#div1").append(foo.value1); 
$("#div2").append(foo.value2); 

Note that some javascript libraries (like jQuery) provide safer ways to handle json than using eval, feel free to use those instead.

请注意,一些javascript库(如jQuery)提供了比使用eval更安全的方式来处理json,请随意使用它们。

#1


4  

Return json in your controller (e.g., add a format.json stanza and request that instead of the .js one). Then in your createSuccessHandler function you'll do something like:

在你的控制器中返回json(例如,添加一个format.json节并请求而不是.js节)。然后在您的createSuccessHandler函数中,您将执行以下操作:

var foo = eval(data);
$("#div1").append(foo.value1); 
$("#div2").append(foo.value2); 

Note that some javascript libraries (like jQuery) provide safer ways to handle json than using eval, feel free to use those instead.

请注意,一些javascript库(如jQuery)提供了比使用eval更安全的方式来处理json,请随意使用它们。