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

当使用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' }); 

任何帮助将不胜感激。

filter()find()取决于检索到的HTML页面的结构。 例如,如果这是检索到的页面:

    Foo   
content
tooltip

如果你想选择顶层元素= 直接子元素 – 在这个例子中: #wrap#tooltip – 那么你必须使用filter()

如果你想选择其他元素 – 在这个例子中: #header

#body ,… – 那么你必须使用find()

我不知道你的元素是否是的孩子,你可以使用这个“hack”:

$("

").html(data).find( selector );

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

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("
") // 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 = $('
').html(data).find('#foo'); // This looks like it'll work!

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

由于@Matt,这就是我能够让它工作的方式

 $.ajax({ type: "GET", url: url, dataType: 'html', success: function(data) { $('#foo').html( $('
').html(data).find('#foo').html() ); } });

如果你不需要完整的$.ajax方法给出的任何特殊function,你应该尝试$.load()

与$ .get()不同,.load()方法允许我们指定要插入的远程文档的一部分。 这是通过url参数的特殊语法实现的。 如果字符串中包含一个或多个空格字符,则假定第一个空格后面的字符串部分是确定要加载的内容的jQuery选择器。

 $('#result').load('ajax/test.html #container'); 

http://api.jquery.com/load/#loading-page-fragments

使用

 $(data).filter("#foo").text(); 

我用它来过滤返回HTML conent的ajax调用的结果