在使用jQuery.ajax()方法时,我很难过滤返回的数据以获得所需的内容。我知道使用.load()和其他jQuery AJAX方法很容易做到这一点,但我需要特别使用.ajax()。
例如,我知道这是可行的;
var title = $(data).filter('title'); // Returns the page title但是如果我只想要一个带有id="foo“的div的内容呢?
var foo = $(data).filter('#foo'); // None of these work
var foo = $(data).find('#foo'); //
var foo = $('#foo', data); //理想情况下,我需要一种方法,可以传入一个普通的jQuery选择器,用于选择标题、div或jQuery可以选择的任何其他元素。这是因为我可以将任何字符串传入到我自己的ajax函数中-例如;
myApp.ajax({
url: 'myPage.html',
filterTitle: 'title',
filterContent: '#main-content'
});任何帮助都将不胜感激。
发布于 2010-11-22 20:20:22
filter()与find()的使用取决于检索到的HTML页的结构。例如,如果这是检索到的页面:
<!DOCTYPE html>
<html>
<head>
<title>Foo</title>
</head>
<body>
<div id="wrap">
<div id="header">
<h1>Foo</h1>
</div>
<div id="body"> content </div>
</div>
<div id="tooltip"> tooltip </div>
</body>
</html> 如果您想选择顶级的elements = elements,它们是<body>的直接子元素--在本例中是:#wrap或#tooltip --那么您必须使用filter()。
如果要选择其他元素-在本例中为:#header、<h1>、#body等... -则必须使用find()。
如果你不知道你的元素是否是<body>的子元素,你可以使用这个"hack":
$("<div>").html(data).find( selector );
通过使用此变通方法,您始终可以通过find()获取元素。
发布于 2010-11-22 20:15:33
jQuery.load方法使用以下代码:
// If successful, inject the HTML into all the matched elements
if ( status === "success" || status === "notmodified" ) {
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div />")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
}也就是说,它将完整的响应附加到它创建的DIV,然后在上面使用find(selector)。
所以你应该会看到类似这样的东西:
var foo = $('<div />').html(data).find('#foo'); // This looks like it'll work!从jQuery的角度来看,这有点像黑客!
发布于 2015-01-28 16:46:47
这就是我能够让它工作的原因,感谢@Matt
$.ajax({
type: "GET",
url: url,
dataType: 'html',
success: function(data) {
$('#foo').html(
$('<div />').html(data).find('#foo').html()
);
}
});https://stackoverflow.com/questions/4245231
复制相似问题