【问题标题】:Ajax request to rails server using jQuery with phonegap not working使用带有phonegap的jQuery对rails服务器的Ajax请求不起作用
【发布时间】:2011-08-07 12:34:55
【问题描述】:

我正在尝试从 iOS 上的 Phonegap 应用向 Rails Restful API 发送登录请求。
以下代码适用于 jQuery 1.5,但不适用于 jQuery 1.4.2。

有人知道为什么会这样吗?

$.ajax({
type: 'POST', url: urlFactory.getLoginURL(),
data: { 'email': emailVal, 'password': passwordVal },
success: onSuccess,
error: onError, dataType: "json"
});

网络服务器给我以下错误:

Started POST "/login.json" for 127.0.0.1 at Mon Apr 18 00:29:38 +0100 2011
Processing by SessionsController#create as JSON
Parameters: {"password"=>"[FILTERED]", "email"=>"example@gmail.com"}
User Load (0.3ms) SELECT users.* FROM users WHERE (users.id IS NULL) LIMIT 1
Completed in 251ms
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
app/controllers/application_controller.rb:37:in require_authorisation_happened'
Rendered /usr/local/lib/ruby/gems/1.8/gems/actionpack- 3.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (2.4ms)
Rendered /usr/local/lib/ruby/gems/1.8/gems/actionpack- 3.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (14.1ms)
Rendered /usr/local/lib/ruby/gems/1.8/gems/actionpack- 3.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (23.4ms)

成功后返回如下:

Started POST "/login.json" for 127.0.0.1 at Mon Apr 18 00:16:25 +0100 2011
Processing by SessionsController#create as JSON
Parameters: {"password"=>"[FILTERED]", "email"=>"example@gmail.com"}
User Load (0.3ms) SELECT
users.* FROMusersWHERE (users.idIS NULL) LIMIT 1
User Load (19.4ms) SELECT
users.* FROMusersWHERE (users.email= 'example@gmail.com') 限制 1
在 306 毫秒内完成 200 次 OK(查看次数:4.6 毫秒 | ActiveRecord:19.7 毫秒)

【问题讨论】:

    标签: jquery ruby-on-rails ajax cordova


    【解决方案1】:

    您缺少真实性令牌。在 rails2 中,您可以在视图中使用 form_authenticity_token 来呈现真实性令牌,然后您需要将其添加到表单提交的参数中。

    在 Rails3 中它更容易。只需在布局的头部添加 ,然后确保使用 rails.js 库用于 ajax。这将获取真实性令牌并将其与表单一起提交。

    这里有一篇简短的文章http://www.themodestrubyist.com/2010/02/24/rails-3-ujs-and-csrf-meta-tags/

    这里有一个示例应用程序https://github.com/grigio/rails3-ujs-demo.git

    【讨论】:

    • 感谢您的回复。据我了解,rails.js 用于文件上传。实际上,它只有在检测到提交表单中的文件类型时才会执行某些操作。此外,在 rails3 默认情况下,csrf 令牌在 json 请求中被关闭。另外,我认为它没有解释为什么它适用于 jquery 1.5 而是 1.4.2。
    • Rails.js 启用不显眼的 javascript 脚本 (UJS) 并解释 Rails 数据属性,获取 csrf_meta_tag 并与实现 :remote => true 的 Rails 助手一起使用。但是 rails.js 不适用于 jQuery 1.4.2 仅 1.4.3 或更高版本。
    • 好的。谢谢你的回答我想我现在知道问题所在了。我认为rails关闭了json的protect_from_forgery选项,但似乎没有。之所以能和jquery 1.5一起工作,是因为rails 3.04之前的版本有一个问题,就是protect_from_forgery在特定条件下不能工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多