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);
            });
          }
        })
      });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)