Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - 在AJAX调用中处理数据类型(Handling Datatype in AJAX call)

I'm trying for hours to get my AJAX call to reach success, and the bug seem lie in the dataType the AJAX call is expecting/I'm sending (JS vs JSON).

(我试图花费几个小时来获得成功的AJAX调用,但错误似乎出在AJAX调用期望/我发送的dataType中(JS与JSON)。)

Unfortunately, I don't know how to solve this.

(不幸的是,我不知道该如何解决。)

When I look at the console.log result of my error I see:

(当我查看错误的console.log结果时,我看到:)

abort: ? ( statusText )
always: ? ()
complete: ? ()
done: ? ()
error: ? ()
fail: ? ()
getAllResponseHeaders: ? ()
getResponseHeader: ? ( key )
overrideMimeType: ? ( type )
pipe: ? ( /* fnDone, fnFail, fnProgress */ )
progress: ? ()
promise: ? ( obj )
readyState: 4
responseText: 
  "var selectList = document.getElementById('reservation_accommodation_id')
  console.log selectList
  function empty() {
    selectList.innerHTML = "";
  }

  empty();

        selectList.insertAdjacentHTML('beforeend', '<optgroup label=Best acco ever>');
            selectList.insertAdjacentHTML('beforeend', '<option value="8">3</option>');
        selectList.insertAdjacentHTML('beforeend', '<optgroup>');
        selectList.insertAdjacentHTML('beforeend', '<optgroup label=Test acco>');
            selectList.insertAdjacentHTML('beforeend', '<option value="16">1</option>');
        selectList.insertAdjacentHTML('beforeend', '<optgroup>');"
setRequestHeader: ? ( name, value )
state: ? ()
status: 200
statusCode: ? ( map )
statusText: "OK"
success: ? ()
then: ? ( /* fnDone, fnFail, fnProgress */ )
__proto__: Object

Code

()

reservations/new.html.erb

(Reservations / new.html.erb)

<%= simple_form_for [@hotel, @reservation] do |f|%>
  <div class="col col-sm-3">
    <%= f.input :arrival,
    as: :string,
    label:false,
    placeholder: "From",
    wrapper_html: { class: "inline_field_wrapper" },
    input_html:{ id: "start_date"} %>
  </div>
  <div class="col col-sm-3">
    <%= f.input :departure,
    as: :string,
    label:false,
    placeholder: "From",
    wrapper_html: { class: "inline_field_wrapper" },
    input_html:{ id: "end_date"} %>
  </div>

  <div class="col col-sm-4">
    <%= f.input :room_id, collection: @room_categories.order(:name), as: :grouped_select, group_method: :rooms,  label:false %>
  </div>

  <%= f.button :submit, "Search", class: "create-reservation-btn"%>
<% end %>

script for reservations/new.html.erb

(Reservations / new.html.erb的脚本)

<script>
const checkIn = document.querySelector('#start_date');
const checkOut = document.querySelector('#end_date');
const checkInAndOut = [checkIn, checkOut];

checkInAndOut.forEach((item) => {
  item.addEventListener('change', (event) => {
    checkAvailability();
  })
})

  function checkAvailability(){

    $.ajax({
      url: "<%= rooms_availability_hotel_path(@hotel) %>" ,
      dataType: 'json',
      type: "POST",
      data: `arrival=${start_date.value}&departure=${end_date.value}`,
      success: function(data) {
        console.log('succes')
        console.log(data);
      },
      error: function(response) {
        console.log('failure')
        console.log(response);
      }
    });
  };
</script>

hotels_controller

(hotels_controller)

def rooms_availability
  hotel = Hotel.includes(:rooms).find(params[:id])
  arrival = Date.parse room_params[:arrival]
  departure = Date.parse room_params[:departure]
  time_span = arrival..departure
  @unavailable_rooms = Room.joins(:reservations).where(reservations: {hotel: hotel}).where("reservations.arrival <= ? AND ? >= reservations.departure", arrival, departure).distinct
  @hotel_cats = hotel.room_categories
  @hotel_rooms = Room.where(room_category: hotel_cats)
  @rooms = hotel_rooms - @unavailable_rooms
  respond_to do |format|
    format.js
  end
end

def room_params
  params.permit(:arrival, :departure, :format, :id)
end

hotels/rooms_availability.js.erb

(hotels / rooms_availability.js.erb)

var selectList = document.getElementById('reservation_room_id')

function empty() {
  selectList.innerHTML = "";
}

empty();


    <% unless @rooms.empty? %>
      <% @hotel_cats.each do |cat|%>
        selectList.insertAdjacentHTML('beforeend', '<optgroup label=<%= cat.name %>>');
        <% cat.rooms.each do |room|%>
          <% if @rooms.include? room %>
            selectList.insertAdjacentHTML('beforeend', '<option value="<%= room.id %>"><%= room.name %></option>');
          <% end %>
        <% end %>
        selectList.insertAdjacentHTML('beforeend', '<optgroup>');
      <% end %>
    <% end %>

Print screen of form html

(表单html的打印屏幕)

<div class="form-group grouped_select optional reservation_room_id">
  <select class="grouped_select optional" name="reservation[room_id]" id="reservation_room_id">
      <option value=""></option>
    <optgroup label="room category 1">
        <option value="6">1</option>
        <option value="7">2</option>
        <option value="8">3</option>
    </optgroup>
    <optgroup label="room category 2">
        <option value="16">1</option>
    </optgroup>
  </select>
</div>

logs

(日志)

Started POST "/hotels/22/rooms_availability" for ::1 at 2019-11-27 15:05:34 +0100
Processing by HotelsController#rooms_availability as JS
  Parameters: {"arrival"=>"2019-11-27", "departure"=>"", "id"=>"22"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ? /Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
  Hotel Load (0.2ms)  SELECT  "hotels".* FROM "hotels" WHERE "hotels"."id" = $1 LIMIT $2  [["id", 22], ["LIMIT", 1]]
  ? app/controllers/hotels_controller.rb:125
  CACHE Hotel Load (0.0ms)  SELECT  "hotels".* FROM "hotels" WHERE "hotels"."id" = $1 LIMIT $2  [["id", 22], ["LIMIT", 1]]
  ? app/controllers/hotels_controller.rb:103
  RoomCategory Load (0.2ms)  SELECT "room_categories".* FROM "room_categories" WHERE "room_categories"."hotel_id" = $1  [["hotel_id", 22]]
  ? app/controllers/hotels_controller.rb:103
  Room Load (0.2ms)  SELECT "rooms".* FROM "rooms" WHERE "rooms"."room_category_id" IN ($1, $2)  [["room_category_id", 4], ["room_category_id", 9]]
  ? app/controllers/hotels_controller.rb:103
Completed 500 Internal Server Error in 13ms (ActiveRecord: 0.9ms)



ArgumentError (invalid date):

app/controllers/hotels_controller.rb:108:in `parse'
app/controllers/hotels_controller.rb:108:in `rooms_availability'
Started POST "/hotels/22/rooms_availability" for ::1 at 2019-11-27 15:05:36 +0100
Processing by HotelsController#rooms_availability as JS
  Parameters: {"arrival"=>"2019-11-27", "departure"=>"2019-11-28", "id"=>"22"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ? /Users/username/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
  Hotel Load (0.3ms)  SELECT  "hotels".* FROM "hotels" WHERE "hotels"."id" = $1 LIMIT $2  [["id", 22], ["LIMIT", 1]]
  ? app/controllers/hotels_controller.rb:125
  CACHE Hotel Load (0.0ms)  SELECT  "hotels".* FROM "hotels" WHERE "hotels"."id" = $1 LIMIT $2  [["id", 22], ["LIMIT", 1]]
  ? app/controllers/hotels_controller.rb:103
  RoomCategory Load (0.3ms)  SELECT "room_categories".* FROM "room_categories" WHERE "room_categories"."hotel_id" = $1  [["hotel_id", 22]]
  ? app/controllers/hotels_controller.rb:103
  Room Load (0.3ms)  SELECT "rooms".* FROM "rooms" WHERE "rooms"."room_category_id" IN ($1, $2)  [["room_category_id", 4], ["room_category_id", 9]]
  ? app/controllers/hotels_controller.rb:103
  Room Load (0.4ms)  SELECT "rooms".* FROM "rooms" WHERE "rooms"."room_category_id" IN (SELECT "room_categories"."id" FROM "room_categories" WHERE "room_categories"."hotel_id" = $1)  [["hotel_id", 22]]
  ? app/controllers/hotels_controller.rb:115
  Room Load (0.9ms)  SELECT DISTINCT "rooms".* FROM "rooms" INNER JOIN "reservations" ON "reservations"."room_id" = "rooms"."id" WHERE "reservations"."hotel_id" = $1 AND (reservations.arrival <= '2019-11-27' AND '2019-11-28' >= reservations.departure)  [["hotel_id", 22]]
  ? app/controllers/hotels_controller.rb:115
  Rendering hotels/rooms_availability.js.erb
  Rendered hotels/rooms_availability.js.erb (0.6ms)
Completed 200 OK in 26ms (Views: 13.8ms | ActiveRecord: 2.4ms)

  ask by techquestion translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

from your console log it's visible that line 108 has the problem.

(从控制台日志中可以看到第108行有问题。)

The problem is that: when you pass either arrival or departure as an empty string "" , then

(问题是:当您将arrivaldeparture作为空字符串""传递arrival ,则)

Date.parse ""

will give you ArgumentError: invalid date .

(将为您提供ArgumentError: invalid date 。)

Try to check those values before do the parsing or use a begin..rescue block.

(尝试在解析之前检查这些值,或使用begin..rescue块。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...