weixin_33670786 2017-04-04 11:49 采纳率: 0%
浏览 316

页面加载后加载ajax

This is the first time that I'm using ajax with jquery and I'm new on jquery I have a structure

$(document).ready(function(){
  data_url = $('.lazy_content').attr("data-url");
    data_id = $('.lazy_content').attr("data-target-id");

    $.ajax({
        url: data_url,
        type: "POST",
        beforeSend: function() {
            $(".loaderDiv").show();
            $("#" + data_id).html("");
        },
        success: function(data) {
            $(data).each(function(index, el) {
                $(".loaderDiv").hide();
                $("#" + data_id).html(data);
            });
        }
    });
});
<div class="lazy_content" data-url="/ajax/yorumlar/@Model.OtelBilgileri.seflink" data-target-id="ajax-content-1">
  <h4 class="tur-main-baslik">COMMENTS</h4>
  <div id="ajax-content-1"></div>
</div>

<div class="lazy_content" data-url="/ajax/trustyou/@Model.OtelBilgileri.seflink" data-target-id="ajax-content-2">
  <h4 class="tur-main-baslik section-head">POSTS</h4>
  <div id="ajax-content-2"></div>
</div>

as you see I have data-url this data url has my ajax-file and I'm getting my ajax file but after page loading nothing work..whats wrong with my code ?

</div>
  • 写回答

3条回答 默认 最新

  • python小菜 2017-04-04 11:53
    关注

    Depending on where the javascript is in the HTML the DOM may not have loaded at the point you run the script.

    encapsulating your javascript within the jquery 'on DOM loaded' function ( $(document).ready( function() { ) will fix that problem, code as follows.

    $(document).ready( function() {
      $('.lazy_content').on("load", function() {
        data_url = $(this).attr("data-url");
        data_id = $(this).attr("data-target-id");
    
        $.ajax({
          url: data_url,
          type: "POST",
          beforeSend: function() {
            $(".loaderDiv").show();
            $("#" + data_id).html("");
          },
          success: function(data) {
            $(data).each(function(index, el) {
              $(".loaderDiv").hide();
              $("#" + data_id).html(data);
            });
          }
        })
      });
    });
    
    评论

报告相同问题?