Question: Question:
I'm using Rails 3.2.
I get it with ajax and process it with hoge.js.erb.
Specifically, we will add more products, and finally POST with submit.
In rare cases, the server returns 304 when adding a product, but the display on the screen is the added behavior regardless of whether it is 200 or 304.
However, the product that returned 304 at POST will be missing (not included in the parameter).
My possible idea is
- When 304 is returned, do not draw on the browser side and issue a message like "An error has occurred. Please add again"
- Only at the time of ajax_fire_item action, 304 is not returned on the server side, and it is set to 200.
is.
The source is shown below.
Ignition part html.erb
function ajax_fire_item(item_id) {
$.get('<%= root_path -%>bills/ajax_fire_item', {pet_id: <%= @pet.id -%>, item_id: item_id});
}
controller
def ajax_fire_item
@pet = Pet.find(params[:pet_id])
@master_item = MasterItem.find(params[:item_id])
end
ajax_fire_item.js.erb
<% form_for([@pet, @pet.bills.build]) do |f|
fields = f.fields_for(:bill_items, BillItem.new(master_item_id: @master_item.id, quantity: 1), :child_index => Time.now.to_i) do |builder|
render("bill_item_fields", :f => builder)
end
@fields = j fields
end %>
var $item = $("<%= @fields -%>");
$item.appendTo('#item_list');
calcRow($item); // 横計
reCalc(); // 合計欄
I tried to make html.erb of the ignition part as follows, but 111 was displayed even if it failed in the log.
function ajax_fire_item(item_id) {
$.ajax('<%= root_path -%>bills/ajax_fire_item',{
data: {pet_id: <%= @pet.id -%>, item_id: item_id},
type: 'GET',
success: function (data, status, xhr) {
// 成功処理
console.log(111);
},
error: function (data, status, xhr) {
// 失敗処理. 304error はココに来る!?
console.log(222);
}
}
);
}
Answer: Answer:
I haven't executed it, so it's just a guess …
If 304 Not modified is returned, the view should be generated from the cache.
In other words, the item is added even if it is 304 on the screen, but it seems that the HTML is the one that was cached last time. The point is that the code below is not unique.
:child_index => Time.now.to_i
Try adding some items and see if the field name of the item with 304 is duplicated with other items. If there are duplicates, that is the cause. Duplicate parameters are merged at POST.
The workaround is to use the $ .ajax method instead of $ .get and optionally
cache: false
If you specify, 304 will not occur.
https://stackoverflow.com/questions/8841425/how-to-set-cache-false-in-jquery-get-call
(However, I feel that it is a little tricky, so it may be necessary to fix it fundamentally …)