开发者

How can I improve my Rails 3 / jQuery / AJAX approach on calling an action from a hyperlink?

I am retrofitting some code to a Rails 2.3.8 application. The whole app uses Prototype, but I need to add some functionality to one controller and its views, so I am switching the old prototype code to jQuery and using a different layout.

So I can't use link_to_remote in these views any more. I have a situation where I need to "clear out" an attribute for the record in question, in an "edit" action.

I have created a hyperlink with a specific id and bound the click function to it in application.js. I have appended the na开发者_开发问答me of the attribute to the end of this specific id.

So I have two things going into this "remove_attribute" action. I need the id of the record, and the name of the attribute.

I am just serializing the form and submitting. But I need to the add the id of the hyperlinked I clicked!

In my application.js, I have:

hash = { type: "POST", url: "/vehicle_applications/remove", data: $("#myform").serialize() };
$.ajax(hash);
return false;

But you can see that I don't have the id of the hyperlink in there. I know that to get the id of the hyperlink I refer to:

$(this).attr('id')

But my question is, how do I get a variable name and that value appended on to the results of $("#myform").serialize()?

Also, how screwed up is my approach?


jQuery's serialize produces a query string:

The .serialize() method creates a text string in standard URL-encoded notation.
[...]
a=1&b=2&c=3&d=4&e=5

So you just need to append another component:

var data = $('#myform').serialize();
if(data)
    data += '&id=' + encodeURIComponent($(this).attr('id'));
else
    data = 'id=' + encodeURIComponent($(this).attr('id'));
$.ajax({
    url: '/vehicle_applications/remove',
    type: 'post',
    data: data
});

Depending on your routes, you might want to id in the URL:

$.ajax({
    url: 'vehicle_applications/remove/' + encodeURIComponent($(this).attr('id')),
    type: 'post',
    data: $('#myform').serialize()
});

This version should be more typical for Rails and RESTful routing but I don't know what your routes look like.


I think a really good option for you to consider is rjs. Its a very nice way to do restful ajax that is baked right into the rails framework:

Have a look at this railscast

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜