【问题标题】:how to do the same thing that load() with xhr?如何用 xhr 做与 load() 相同的事情?
【发布时间】:2013-01-13 00:42:23
【问题描述】:

我有这个代码 load:

    $('#single-photo-zoom').load(href+' #content', function() {
        alert("ok");
    });

我想使用$.ajax,但不知道如何在#single-photo-zoom中加载#content

  xhr = $.ajax({
        url: href,
        success: function(data) {
             // ???
        }
    });

我想使用$.ajax,因为我希望有可能中止加载。 load 函数是不可能的。

【问题讨论】:

    标签: jquery ajax load xmlhttprequest abort


    【解决方案1】:

    如果您知道负载的作用,那就太容易了。

    xhr = $.ajax({
        url: href,
        success: function(data) {
             $('#single-photo-zoom').html(data);
        }
    });
    

    【讨论】:

    • 这里的数据是什么?我想在$('#single-photo-zoom').html();中加载#content
    • data是ajax调用返回的内容。我认为 charlietfl 版本效果更好
    【解决方案2】:

    首先将数据转换为一个jQuery对象,然后可以从该对象中检索你想要的内容并插入到适当的元素中:

    success:function(data){
        var $content=$(data).find('#content');
        $('#single-photo-zoom').html( $content);
    }
    

    编辑:

    假设 #content 在另一个父级中,例如 body 或另一个 div 。如果不是整页并且#content 处于根级别,请使用filter() 而不是find()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多