javascript – I want to handle "304 Not Modified"

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.


The source is shown below.

Ignition part html.erb

function ajax_fire_item(item_id) {
  $.get('<%= root_path -%>bills/ajax_fire_item', {pet_id: <%= -%>, item_id: item_id});


def ajax_fire_item
  @pet = Pet.find(params[:pet_id])
  @master_item = MasterItem.find(params[:item_id])


<% form_for([@pet,]) do |f|
  fields = f.fields_for(:bill_items,, quantity: 1), :child_index => do |builder|
    render("bill_item_fields", :f => builder)
  @fields = j fields
end %>
var $item = $("<%= @fields -%>");

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: <%= -%>, item_id: item_id},
      type: 'GET',
      success: function (data, status, xhr) {
        // 成功処理
      error: function (data, status, xhr) {
        // 失敗処理. 304error はココに来る!?

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 =>

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.

(However, I feel that it is a little tricky, so it may be necessary to fix it fundamentally …)

Scroll to Top