如何执行一个Ajax请求在Rails 3的加载页面的创建操作? [英] How do I perform an Ajax request to the create action on loading a page in Rails 3?

查看:97
本文介绍了如何执行一个Ajax请求在Rails 3的加载页面的创建操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails应用程序链接了Twitter的API(使用Twitter的宝石)。

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

一个用户输入的网页上,他们的用户名,在创造的行动做了Twitter的API调用和计算,在此之后,新的记录被保存,秀的行动被加载。

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' action is loaded.

如果用户已经存在的存在不需要API调用,它会重定向直接到秀。

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

由于计算需要一段时间,我想最好的方法是为显示用户的页面(如本地主机/用户/用户名)的加载动画,调用行动执行通过Ajax Twitter API的任务,然后再输出结果与JS

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.

我没有经验使用Ajax和Rails之前和我看过任何教程往往处理的形式提交相同的页面,其中,因为这是略有不同的。

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.

鸭preciate任何帮助或指针或建议,如果有这个一个更好的做法。

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

我使用jQuery。

推荐答案

我的建议是创建一个jQuery功能ping您的服务器每隔几秒钟检查,如果Twitter的API调用完成。这样,你可以ping服务器导致确认时加载动画加载用户的主页,然后只需删除动画或完成一些其他动作。

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.

要做到这一点,你可能必须有一个方法来保存用户的Twitter API调用的状态。一个简单的方法,这样做将有存储呼叫的状态,您的用户对象的属性(0 =待定,1 =成功,2 =错误)的例子。

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.

您可以再脱掉你的服务器上的任务,这将使调用Twitter和填充API调用属性。客户端将ping服务器的状态code,然后采取适当的行动(继续显示动画,重定向,显示错误,...)

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, ...)

这篇关于如何执行一个Ajax请求在Rails 3的加载页面的创建操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆