如何从jQuery.ajax()过滤返回的数据?

smi*_*x96 20 ajax jquery filter

使用该jQuery.ajax()方法时,我正在努力过滤返回的数据以获得我所需要的.我知道这很容易使用.load(),可能还有其他jQuery AJAX方法,但我需要.ajax()具体使用.

例如,我知道这有效;

var title = $(data).filter('title'); // Returns the page title
Run Code Online (Sandbox Code Playgroud)

但是,如果我只想要id为"foo"的div的内容呢?

var foo = $(data).filter('#foo'); // None of these work
var foo = $(data).find('#foo');   //
var foo = $('#foo', data);        //
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想要一个方法,我可以传递一个普通的jQuery选择器,它将用于选择标题,div或jQuery可以选择的任何其他元素.这样我就可以将任何字符串传入我自己的ajax函数 - 例如;

myApp.ajax({
    url: 'myPage.html',
    filterTitle: 'title',
    filterContent: '#main-content'
});
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Šim*_*das 19

filter()vs 的使用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>  
Run Code Online (Sandbox Code Playgroud)

如果要选择顶级元素=直接子元素<body>- 在此示例中为:#wrap#tooltip- 则必须使用filter().

如果要选择其他元素-在这个例子:#header,<h1>,#body,... -那么你必须使用find().

我不知道你的元素是否是孩子<body>,你可以使用这个"hack":

$("<div>").html(data).find( selector );

通过使用此解决方法,您始终可以获取元素find().


Mat*_*att 7

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 );
}
Run Code Online (Sandbox Code Playgroud)

即它将完整的响应附加到它创建的DIV,然后使用find(selector)它.

所以你应该看看像这样的东西:

var foo = $('<div />').html(data).find('#foo'); // This looks like it'll work!
Run Code Online (Sandbox Code Playgroud)

从jQuery的角度来看,这是一个黑客攻击!