简单的jQuery ajax的例子中没有发现在返回的HTML元素 [英] Simple jQuery ajax example not finding elements in returned HTML
问题描述
我想学习jQuery的Ajax功能。我有工作,但jQuery的没有发现,在返回的HTML DOM元素。在同一文件夹中的jQuery,运行这个页面:
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:
<!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:
Which loads this page "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中。我究竟做错了什么?
It gives two alerts. One showing the DOM was loaded, but the second shows NULL instead of the #wrapper. What am I doing wrong?
编辑:我加载ajaxtest,load.html,它包括整个头,又包括jQuery的。是这个问题?
I'm loading "ajaxtest-load.html" which includes the whole header, including jquery again. Is that the issue?
推荐答案
我已经成功使用 .load()
。
要创建具有提取HTML的新块到DOM我这样做:
To create a new block with extracted html into the DOM I do this:
$('<div></div>').appendTo('body').load('some-other-document.html div#contents');
如果它不为你工作,确保你使用的是最新的版本(或发布1.2)的jQuery。请参阅文档.load 获得更多的例子。
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 .load for more examples.
编辑:
请注意,虽然,与上述例子的结果将是:
Note, though, that with the above example the result will be:
<div><div id="contents">...</div></div>
要获取的#contents DIV只是内容的其他文件中,在加载函数调用使用一个回调函数。
To get just the contents of the #contents div in the other document, use a callback-function in the load-function call.
$('<div></div>').load('some-other-document.html div#contents', null,
function (responseText, textStatus, XMLHttpRequest) {
if (textStatus == success) {
$('<div></div>').appendTo('body').html($(this).html());
}
}
);
这篇关于简单的jQuery ajax的例子中没有发现在返回的HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!