简单的 jQuery ajax 示例在返回的 HTML 中找不到元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1033460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:27:35  来源:igfitidea点击:

Simple jQuery ajax example not finding elements in returned HTML

jqueryajaxdomparsing

提问by user110218

I'm trying to learn jQuery's ajax functions. I've got it working, but jQuery doesn't find elements in the returned HTML DOM. In the same folder as jquery, run this page:

我正在尝试学习 jQuery 的 ajax 函数。我已经开始工作了,但是 jQuery 在返回的 HTML DOM 中找不到元素。在与 jquery 相同的文件夹中,运行此页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
    <title>runthis</title>

    <script type="text/javascript" language="javascript" src="jquery-1.3.2.min.js"></script>

    <script tyle="text/javascript">
    $(document).ready(function(){
        $('input').click(function(){
            $.ajax({
                type : "GET",
                url : 'ajaxtest-load.html',
                dataType : "html",
                success: function(data) {

                alert( data ); // shows whole dom

                alert( $(data).find('#wrapper').html() ); // returns null

                },
                error : function() {
                    alert("Sorry, The requested property could not be found.");
                }
            });
        });
    });
    </script

</head>
<body>
    <input type="button" value="load" />
</body>
</html>

Which loads this page "ajaxtest-load.html":

加载此页面“ajaxtest-load.html”:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
    <title>load this</title>

</head>
<body>
    <div id="wrapper">
    test
    </div>
</body>
</html>

It gives two alerts. One showing the DOM was loaded, but the second shows NULL instead of the #wrapper. What am I doing wrong?

它给出了两个警报。一个显示 DOM 已加载,但第二个显示 NULL 而不是 #wrapper。我究竟做错了什么?

EDIT: I'm loading "ajaxtest-load.html" which includes the whole header, including jquery again. Is that the issue?

编辑:我正在加载“ajaxtest-load.html”,其中包括整个标题,再次包括 jquery。是这个问题吗?

采纳答案by nikc.org

I've managed to load snippets off of full html-documents just fine by using .load().

我已经设法通过使用.load().

To create a new block with extracted html into the DOM I do this:

要使用提取的 html 到 DOM 创建一个新块,我这样做:

$('<div></div>').appendTo('body').load('some-other-document.html div#contents');

If it's not working for you, make sure you're using the most recent version (or post 1.2) of jQuery. See the documentation for .loadfor more examples.

如果它不适合您,请确保您使用的是最新版本(或 1.2 版)的 jQuery。有关更多示例,请参阅.load文档

Edit:

编辑:

Note, though, that with the above example the result will be:

但是请注意,对于上面的示例,结果将是:

<div><div id="contents">...</div></div>

To get just the contents of the #contents div in the other document, use a callback-function in the load-function call.

要仅获取其他文档中 #contents div 的内容,请在加载函数调用中使用回调函数。

$('<div></div>').load('some-other-document.html div#contents', null, 
    function (responseText, textStatus, XMLHttpRequest) {
        if (textStatus == success) {
            $('<div></div>').appendTo('body').html($(this).html());
        }
    }
);

回答by rakensi

This is not a direct answer, but may help to clarify things.

这不是一个直接的答案,但可能有助于澄清事情。

The data parameter of the callback function can be made into a jQuery (1.6.2) object $(data), which contains the different parts of the HTML response:

回调函数的 data 参数可以做成一个 jQuery (1.6.2) 对象 $(data),它包含了 HTML 响应的不同部分:

  • Stuff that precedes the actual document, such as a doctype declaration, or ignorable white space textnodes.
  • The contents of the head element.
  • The contents of the body element.
  • 实际文档之前的内容,例如 doctype 声明或可忽略的空白文本节点。
  • head 元素的内容。
  • body 元素的内容。

The html, head and body elements are not in the data object. Since the number of elements contained in head and body may vary, you should not get them by indexing like $(data)[2]. Instead, apply a filter to this object, like this:

html、head 和 body 元素不在数据对象中。由于 head 和 body 中包含的元素数量可能会有所不同,因此您不应通过像 $(data)[2] 那样的索引来获取它们。相反,将过滤器应用于此对象,如下所示:

        $.get(
          uri,
          function(data, textStatus, jqXHR){
            var $doc = $(data);
            var title = $doc.filter('title').text();
            // title is the title from the head element.
            // Do whatever you need to do here.
          }
        );

After filtering the right elements, you can apply further selectors using find().

过滤正确的元素后,您可以使用 find() 应用更多选择器。

Unfortunately, in IE the head elements are not part of $(data). I have no idea why this is.

不幸的是,在 IE 中,头部元素不是 $(data) 的一部分。我不知道这是为什么。

回答by MSpreij

I found that if ajaxtest-load.html does not have <html> or <body> tags but just a few html elements, it doeswork.

我发现如果 ajaxtest-load.html 没有 <html> 或 <body> 标签而只有几个 html 元素,它确实可以工作。

Edit:

编辑:

If the input has to be a full HTML page, maybe you can first strip of the tags you don't want with string operations.. anyone?

如果输入必须是一个完整的 HTML 页面,也许你可以先用字符串操作去掉你不想要的标签..有人吗?

Edit 2:

编辑2:

Vaguely remembered Javascript/DOM allowed for "temporary documents" which you could operate on and use the results from, then a bit of googling yielded a parseHTML function (http://www.daniweb.com/forums/post874892-2.html) which I've adapted to return the right bit:

模糊地记得 Javascript/DOM 允许您可以操作并使用其结果的“临时文档”,然后一些谷歌搜索产生了一个 parseHTML 函数(http://www.daniweb.com/forums/post874892-2.html)我已经适应返回正确的位:

$(document).ready(function(){
  $('input').click(function(){
    $.ajax({
      type : "POST",
      url : 'ajaxtest-load.html',
      dataType : "html",
      success: function(data) {
        alert( data ); // shows whole dom
        var gotcha = parseHTML(data, 'wrapper');
        if (gotcha) {
          alert($(gotcha).html());
        }else{
          alert('ID not found.');
        }
      },
      error : function() {
        alert("Sorry, The requested property could not be found.");
      }
    });
  });
});

function parseHTML(html, idStr) {
  var root = document.createElement("div");
  root.innerHTML = html;
  // Get all child nodes of root div
  var allChilds = root.childNodes;
  for (var i = 0; i < allChilds.length; i++) {
    if (allChilds[i].id && allChilds[i].id == idStr) {
      return allChilds[i];
    }
  }
  return false;
}

Does that work?

那样有用吗?

回答by karim79

Why not try this and see what happens:

为什么不试试这个,看看会发生什么:

$('#testDiv').load('ajaxtest-load.html #wrapper', function(resp) {
    alert(resp);
});

From the $.load documentation:

$.load 文档

In jQuery 1.2 you can now specify a jQuery selector in the URL. Doing so will filter the incoming HTML document, only injecting the elements that match the selector.

在 jQuery 1.2 中,您现在可以在 URL 中指定一个 jQuery 选择器。这样做将过滤传入的 HTML 文档,只注入与选择器匹配的元素。