【问题标题】:rails 3 + jquery post failing?rails 3 + jquery post失败?
【发布时间】:2012-01-02 12:42:22
【问题描述】:

好的,我有一个 rails 3 应用程序,当我尝试对 rails 操作执行 $.post 请求时,系统提示我重新登录...这可能与authenticity_token 或rails 3 处理帖子或远程的方式有关= > 是的……但老实说,我真的不知道为什么它不起作用……这是我的代码

$('#pling').click(function(e){
    e.preventDefault();
    var location = $(this).closest("form").attr("action");
    $.post(location, { note: $("#note").val() }, function(data) {
        var length = data.length;
        var div_string = "";
        for (i=0;i<length;i++)
        {
            div_string += "<p style=\"font-size: 11px; padding: 0 5px;\">"+ data[i].comment.comment +"</p>";
        }
        $("#pling").html(div_string);
    });
    $("#pay").val("");
    $("#pling").animate( { backgroundColor: "#D3ECF4" }, 1 ).animate( { backgroundColor: "#ffffff" }, 3000 );
});

这是我的 Rails 操作

def update_note
  @user = Contact.find(params[:id])
  note = params[:note].to_s.strip
  note = "#{Time.now} - #{note.to_s} - #{current_user.name} (#{current_user.id})"
  @user.notes.create!(:note => note, :user_id => current_user.id)
  respond_to do |format|
    format.json { render :json => @user.notes}
  end
end

知道我做错了什么

如果我查看源代码,这是我的表单

<form method="post" action="/users/100/update_note?remote=true" accept-charset="UTF-8">
<div style="margin:0;padding:0;display:inline">
<input type="hidden" value="✓" name="utf8">
<input type="hidden" value="yPtCzfaI5HOSWeW8HBGLthbpUmgsfgsdfgsdW4aunGDtacva6Kx0=" name="authenticity_token"></div>

【问题讨论】:

  • 它到底是怎么不工作的,有什么错误吗?
  • 旁注。如果是:@user.notes.create!,则无需详述::user_id =&gt; current_user.id
  • 它在我清除缓存后将我从 Safari 中注销......所以基本上是第一次访问该页面......它提示我输入登录名和密码
  • 您在评论中描述的基本上是Rails中csrf反措施后的默认行为。
  • 补充@apneadiving 所说的,确保你安装了这个Rails UJS 适配器,这样它就会通过所有jQuery ajax 调用来传递真实性令牌:github.com/rails/jquery-ujs

标签: jquery ruby-on-rails ajax ruby-on-rails-3 post


【解决方案1】:

不要直接通过 jquery 发帖,而应该使用 rails 的 ujs 助手:

form_for @user, :remote => true

然后将自己插入此处描述的生命周期方法表单http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

【讨论】:

    猜你喜欢
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多