【问题标题】:how to get raw html string with jQuery .get()如何使用 jQuery .get() 获取原始 html 字符串
【发布时间】:2011-12-15 08:52:18
【问题描述】:

我需要获取带有<div> 标签和所有内容的原始html,并将其放入变量字符串中。

所以如果我有一个单独的文件 test.html

<div>
<div><img src="images/htc_hero_wallpaper_01.jpg" width="20%" height="20%" alt="" /></div>
WORKS!!!
</div>

我需要 jQuery 命令

$.ajax({
  url: "test.html",
  success: function(){

 var htmlraw = ?????
 alert(htmlraw)  /// should print the raw test.html
  }
});

打印

<div>
<div><img src="images/htc_hero_wallpaper_01.jpg" width="20%" height="20%" alt="" /></div>
WORKS!!!
</div>

【问题讨论】:

    标签: jquery html ajax get


    【解决方案1】:

    这可能为时已晚,但正确的做法是将fourth parameter to $.get (the dataType) 设置为“文本”:

    $.get("test.html", null, function(html) {
        console.log(html);
    }, "text");
    

    否则,它将自动检测响应是 HTML 并为您解析。

    【讨论】:

      【解决方案2】:
      $.get({
        url: "test.html",
        success: function(data){
      
       var htmlraw = data;
       //alert(htmlraw)  /// should print the raw test.html
       $("#someDiv").html(htmlraw);
        }
      });
      

      【讨论】:

      • [object XMLdocument] 是输出
      • 您是否在本地托管过任何服务器?至少 apache/IIS?
      • 问题可能出在其他地方
      【解决方案3】:

      你应该看看来自 jQuery 的 .html() http://api.jquery.com/html/

      【讨论】:

        【解决方案4】:

        如果要获取文件中特定元素的 html,可以找到该元素并将其附加到新元素。这样,您将能够获得带有.html()的原始html字符串

        $.get("test.html", function(data)
        {
            var specificEl = $(data).find('#specific-element');
            var html = $(document.createElement('div')).append(specificEl).html();
        
            console.log(html);
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-01
          • 1970-01-01
          • 2018-01-25
          • 2014-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多