开发者

How do I get Rails variables from my returned jQuery Ajax data?

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

$.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 |for开发者_如何学Cmat|
  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?

function createSuccessHandler(data) {

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

}

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


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:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜