【问题标题】:.find() in $.ajax response$.ajax 响应中的 .find()
【发布时间】:2012-08-31 23:18:48
【问题描述】:

我只是在执行一个简单的 ajax 请求来获取文件的内容,但是当我尝试获取实际的 <body> 时,它总是什么都不返回。

jQuery.ajax(location).done(function(response) {
    // RETURNS []
    console.log(jQuery(response).find('body'));

    // <body class="html ...">
    // RETURNS []
    console.log(jQuery(response).find('.html'));

    // When I try to get any other div it just works
    // RETURNS THE DIV
    console.log(jQuery(response).find('#header'));
})

【问题讨论】:

  • 响应包含的实际数据是什么?
  • 只是来自网站&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;...的完整html所以源代码
  • location 是否与您的页面在同一个域中?
  • 是的,为了清楚起见,我正在获取文件的实际内容,.find() 方法无法获取&lt;body&gt; 的内容,我可以但是搜索任何 id 或类。
  • 看这里,同样的问题有解决方案:stackoverflow.com/questions/7839889/…

标签: jquery html ajax


【解决方案1】:

jQuery(response) 去掉 htmlheadbody 标签

你需要将你的正文内容包装在一个额外的 div 中并寻找它。

编辑:

jQuery(string) 解析字符串以检查它是选择器还是 html 片段。如果它是一个 html 片段,则字符串被注入到一个空的 div 中,支持 htmlheadbody标签因此被剥离

【讨论】:

  • 如果我使用console.log,我可以看到其中的html、head和body标签,它没有被剥离
  • 您可以看到响应变量中的标签,但 jQuery 会将它们剥离。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 2020-06-11
  • 2013-01-03
  • 2017-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多