开发者

How do I perform an Ajax request to the create action on loading a page in Rails 3?

I have a Rails app that links up with the Twitter API (using the Twitter gem).

A user enters their username on the homepage, the 'create' action does a Twitter API call and a calculation, after which the new record is saved and the 'show' a开发者_Python百科ction is loaded.

If the user already existed there is no API call needed, it will redirect straight to 'show'.

As the calculation takes a while, I'm thinking the best method is to show the user's page (e.g. localhost/user/username) with a loading animation, call an action that performs the Twitter API task via Ajax, then output the results with JS.

I've had no experience with Ajax and Rails before and any tutorials I've looked at tend to deal with forms being submitted on the same page, where as this is slightly different.

Appreciate any help or pointers or suggestions if there is a better practice for this.

I'm using jQuery.


My suggestion would be to create a jQuery function that pings your server every couple of seconds to check if the twitter api call has completed. That way you can load your user home page with the loading animation and then simply remove the animation or complete some other action when pinging the server results in a confirmation.

To accomplish this you'll probably have to have a way to persist the user's Twitter api call state. A simple way to do this would be to have an attribute on your user object that stores the call's state (0 = pending, 1 = success, 2 = error) for example.

You could then kick off a task on your server that would make the call to Twitter and populate the api call attribute. The client would ping the server for the status code and then take appropriate action (continue to show animation, redirect, display error, ...)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜