2012-04-17 42 views
0

我用Rails 3.2.3和我有以下形式Rails的AJAX的形式返回406不接受 - 但只在第二POST请求

<%= form_for(@item, url: list_path, remote: true, html: {id: "item-create-form", class: "form-horizontal"}) do |f| %> 
    <div class="input-append"> 
     <%= f.text_field :description, id: "item-description-input", autofocus: true, placeholder: "Type and press enter." %> 
    </div> 
<% end %> 

的创建与下面的代码操作:

def create 
    @user = User.find_by_username(params[:username]) 
    @item = current_user.items.build(params[:item]) 
    respond_to do |format| 
    if @item.save 
     @item.update_attribute(:vpos, 0) 
     @items = Item.find_all_by_user_id(@user) 
     @items.each do |item| 
     item.update_attribute(:vpos, item.vpos + 1) 
     end 
     format.js 
    else 
     format.js {render "errors" } 
    end 
    end 
end 

相应的js.erb文件在那里并按预期进行渲染。下面的代码:

$('#position-zero').after('<%= escape_javascript(render(:partial => @item)) %>'); 
$('#item-create-form').html('<%= escape_javascript(render(:partial => "item_create_form", :locals => { :@item => Item.new })) %>'); 
$("#item-description-input").focus(); 
$(".best_in_place").best_in_place(); 

我的application.js文件看起来像这样:

//= require jquery 
//= require jquery_ujs 
//= require jquery-ui 
//= require jquery.purr 
//= require best_in_place 
//= require_tree . 
// Loads all Bootstrap javascripts 
//= require bootstrap 

一切都在Chrome和Safari的伟大工程 - 只有HTTP 200个响应。

但是,在Firefox上,第一次表单提交工作正常。但第二个给我一个406 not accepted错误。

检查Firebug时,第一个请求的内容类型设置为text/javascript,但在第二个请求上更改为text/html

我试过在format.js(如:{ render content_type: 'text/javascript' })之后设置内容类型,并在控制器上设置标题(如:headers["Content-Type"] = "text/javascript; charset=utf-8"),但无济于事。

那里有什么好的灵魂可以揭示这个烦人的问题?

+0

你的意思是提交相同的表单两次吗? – Amit 2012-04-17 07:03:29

+0

是的。这是一个列表,您可以在其中键入一个项目,按回车键,该项目将在表单字段下方的列表中创建。 – rapcal 2012-04-17 14:56:55

+0

所以看起来,一旦你提交表单,表单jqueryujs正在做一些事情来搞乱下一个请求。你能检查数据远程attr是否在第一次请求后被修改吗? – Amit 2012-04-18 16:59:27

回答

1

注意你的第二行js.erb?您正在窗体内添加一个窗体。所以基本上当你第二次提交表单时,第一个表单是作为ajax请求发送的,但是,上面的表单不是,会给你提出问题。你应该删除第二行,事情应该没问题

+0

谢谢,阿米特!对不起,我的愚蠢花费了你很多时间......:-S我在表单中添加了一个div,并调用.parent(),所以一切都正在工作。 – rapcal 2012-04-19 21:03:17