每次我发出请求时,Ajax都会显示我的整个HTML

时间:2017-06-21 15:34:09

标签: javascript ruby-on-rails ajax

这是一款rails应用程序,我正试图让我的动态成为我的Gmaps标记...

使用下面的代码,每次执行请求时都会重复我的html ... 我是JS和Ajax的新手,请问我该怎么做才能使它工作?

$(function(){

  $('#normal-choice input').on('click', function(event) {
    var url = '/meals?';
    $.ajax({
      type: "GET",
      url: url,
      data: $('.normal-form').serialize(),
      success: function(data) {
        $('.meals-normal').replaceWith($(data).find('.meals-normal').parent().html()),
        $('#map').replaceWith($(data)).find('#map').updateMarkers(markerJson),

        history.replaceState({}, "meals", url);
      },

      error: function(jqXHR) {
        console.error(jqXHR.responseText);
      }
    });
  });
});

修改

$('#map').replaceWith($(data)).find('#map').updateMarkers(markerJson);不在代码中时,过滤时会很好地显示用餐时的重新加载 当我有这条线的时候......它会弄乱一切......

这是我的一些代码:

这是我的膳食指数观点

<div class="container">
  <div class="row">

    <div class="col-sm-2">
      <section class="choice" id="normal-choice">
        <form action="/meals" method="get" class= "normal-form">
          <ul class="list-unstyled">
            <% @categories.each do |category| %>
              <li>
                <label class="categories">
                  <input type="checkbox" name="categories[]" value="<%= category.name %>"
                    <%= "checked" if !params[:categories].nil? && params[:categories].include?(category.name) %>>

                  <span>
                     <span class="icons text-center">
                        <i class="fa fa-heart" aria-hidden="true"></i>
                     </span>
                    <%= category.name %>
                  </span>

                </label>
              </li>
            <% end %>
          </ul>
          <input class="valid-btn" type="submit" value="Filtrer">
        </form>
      </section>
    </div>

  <div class="col-sm-10">
    <section class="meals-normal">
      <% if @meals_count != 0 %>
        <div class="row">
          <% @meals.sort.each do |meal| %>
            <div class="col-xs-12 col-sm-6 col-md-4">
              <%= link_to meal_path(meal) do %>
              <div class="card-meal">
                <div class="description text-center">
                  <div class="description-meal">
                    <h3><%= meal.menu_name  %></h3>
                    <span><small><%= meal.category.name %></small></span>
                    <br>
                    <% if  meal.images?%>

                      <%= cl_image_tag meal.images.first.path, width: 200, height: 100, crop: :fill %>

                    <% end %>
                    <h4>Cuisiné par: <%= meal.user.nickname %></h4>
                    <p>Prévu pour le: <%= meal.availability %></p>
                  </div>
                  <div class="price-icons">
                    <p> <%= humanized_money_with_symbol(meal.price) %></p>
                  </div>
                </div>
              </div>
            </div>
            <% end %>
          <% end %>
        </div>

      <% else %>
        <p class="no-meal">Aucun repas ne correspond à votre recherche.

         <%= link_to 'Effacer les filtres', meals_path('category[]' => 'all') %>
         </p>
      <% end %>

    </section>
  </div>

  </div>
  <div id="map" style="width: 100%; height: 600px;" data-markers='<%= raw @markers_hash.to_json %>'></div>

</div>

这是我的map.js

var handler = Gmaps.build('Google');

$(document).on('ready', function() {
  if ($('#map').length > 0) {
    var markerJson = $('#map').data('markers');
    drawMeAMap(markerJson);
  }
});

function drawMeAMap(markerJson){
  $('#map').html('');
  handler.buildMap(
    {
      internal: { id: 'map' }

    },
    addMarkers(markerJson),
  );
};

function updateMarkers(markerJson){
  removeMarkers(markerJson);
  addMarkers(markerJson);

};

function removeMarkers(markerJson){
  handler.buildMap({ internal: { id: 'map' } }, function() {
    markers = handler.removeMarkers(markerJson);
    });
};

function addMarkers(markerJson){
  handler.buildMap({ internal: { id: 'map' } }, function() {
    markers = handler.addMarkers(markerJson);
    handler.bounds.extendWith(markers);
    handler.fitMapToBounds();
    if (markers.length == 0) {
      handler.getMap().setZoom(2);
    } else if (markers.length == 1) {
      handler.getMap().setZoom(14);
    }
  });
};

感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

我会尝试以不同的方式回答您当前的答案

1。为你的ajax创建路线,

  • 它取决于您想要实现的目标,如果您想显示数据,那么您使用get
  • 创建路径的数据
  • 如果您想从用户那里获得输入,那么您创建的路线如下所示是获取和发布的示例代码

    resources :some_resources do
    collection {
        get  :get_data 
    }
    end
    resources :some_resources do
    collection {
        post :accept_data  
    }
    

2.使用控制器获取数据

  • 以下控制器示例

    def get_data
       # here you search data to show
    end
    

3。创建链接以调用ajax

  • 在rails中使用ajax的关键是使用关键字remote:true(reference: working with javascript

    <%= link_to 'show data', get_data_some_resources_path, remote: true %>

4。使用js格式创建视图

  • 因为我们使用remote:true,rails会自动渲染 get_data.erb.js 通常没有远程:true rails只会渲染get_data.erb.html(确保你把这个文件放在/ app中/ views / some_resources / folder。
  • 将您的js代码放在此处以显示数据。
  • 通常我使用bootstrap模式用下面的代码显示数据

    // Render the new form
    $('.modal-body').html('<%= j render("pop-up-form.html.erb") %>');
    // Show the dynamic dialog
    $('#dialog').modal("show");