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

2023-11-27

我正在尝试学习 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>

它加载此页面“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>

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

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


这不是直接答案,但可能有助于澄清问题。

回调函数的 data 参数可以制作成 jQuery (1.6.2) 对象 $(data),其中包含 HTML 响应的不同部分:

  • 实际文档之前的内容,例如文档类型声明或可忽略的空白文本节点。
  • head 元素的内容。
  • body 元素的内容。

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.
          }
        );

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

简单的 jQuery ajax 示例未在返回的 HTML 中找到元素 的相关文章

随机推荐