Rails 3 Ajax“Double Post Request”问题

时间:2013-10-02 00:35:20

标签: javascript ruby-on-rails ajax post

我的Ajax在点击时发布了两次(虽然我只期待一次),我似乎无法理解为什么。我认为这可能是一个双重渲染问题,但我对rails非常陌生,需要对哪些方面有所了解?

JS:

$("select[name='order[city]']").on("blur",function() {
    $("#triangle").fadeOut(800);
    $("#cityFee").fadeOut(800);
    if (feeSelected == 80 || feeSelected == 81){
        $.ajax({
            type: "POST",
            url: '/line_items',
            beforeSend: function(xhr){
                xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
            data: {product_id: feeSelected, qty_selected: 1, remote: true},
            dataType: "script"
        });
    }
});

控制器:

def create
 @cart = current_cart

 product = Product.find(params[:product_id])
 ctlQty = params[:qty_selected] #parameter from itemBoxZoom user selected quantity in jquery dialog widget
 @line_item = @cart.add_product(product.id, ctlQty) #passes in user selected quantity   

respond_to do |format|
    if @line_item.save
        format.html { redirect_to(store_index_url) }
        format.js   { @current_item = @line_item }
        format.json { render json: @line_item, status: :created, :location => @line_item }
    else
        format.html { render :action => "new" }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }
    end
end
end

我的模型中调用的方法:

def add_product(product_id, qty_selected)
current_qty = qty_selected || 1

current_item = line_items.find_by_product_id(product_id)    
if current_item
    current_item.quantity += current_qty.to_i
else
    current_item = line_items.build(:product_id => product_id)
    if qty_selected
        current_item.quantity += current_qty.to_i - 1 #removes unnecessary default value of 1
    end
end
qty_selected = nil
current_item
end

在我的控制台中,我看到两个几乎相同的帖子请求到LineItemsController #create,除了第一个执行“INSERT INTO”,第二个请求执行“SET quantity = 2”。所有的建议/帮助非常感谢。感谢

1 个答案:

答案 0 :(得分:1)

如果是双重渲染问题,你会得到一个DoubleRenderError。您是否检查过JavaScript未初始化/调用两次?表单本身是否提交相同的操作?如果是,它是否返回虚假或以其他方式取消表单提交?我看到你正在“提交”模糊的形式。我想知道当你选择值并按Enter键时,它会触发模糊事件并提交表单吗?或者模糊事件被触发两次?

这些只是我开始寻找的地方。