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

我正在尝试学习jQuery的ajax函数。 我有它工作,但jQuery没有在返回的HTML DOM中找到元素。 在与jquery相同的文件夹中,运行此页面:

   runthis   $(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      

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

    load this   
test

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

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

我已经设法通过使用.load()来完整地从完整的html文档中加载片段。

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

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

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

编辑:

但请注意,使用上面的示例,结果将是:

 
...

要仅获取其他文档中#contents div的内容,请在load-function调用中使用callback-function。

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

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

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

  • 在实际文档之前的东西,例如doctype声明或可忽略的空格文本节点。
  • 头元素的内容。
  • 身体元素的内容。

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

  $.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中头元素不是$(数据)的一部分。 我不知道为什么会这样。

我发现如果ajaxtest-load.html没有或标签但只有几个html元素,它确实有效。

编辑:

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

编辑2:

模糊地记住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; } 

那样有用吗?

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

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

从$ .load文档 :

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