2012-04-17 41 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