如何过滤来自jQuery.ajax返回的数据? [英] How do I filter the returned data from jQuery.ajax?

查看:284
本文介绍了如何过滤来自jQuery.ajax返回的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用jQuery.ajax方法,我在努力筛选返回的获得正是我所需要的数据。我知道这是很容易使用.load也可能是其他的jQuery AJAX方法,但我需要使用阿贾克斯具体。

When using the jQuery.ajax method, I am struggling to filter the data that is returned to get exactly what I need. I know this is easy using .load and probably the other jQuery ajax methods but I need to use .ajax specifically.

例如我知道这工作;

var title = $(data).filter('title'); // Returns the page title

但如果我只是想用ID =foo的一个div的内容?

But what if I just want the contents of a div with id="foo"?

var foo = $(data).filter('#foo'); // None of these work
var foo = $(data).find('#foo');   //
var foo = $('#foo', data);        //

理想情况下,欲在其中我可以通过一个正常jQuery选择,这将适用于选择标题,div的,或任何其他元件jQuery可选择的方法。这是为了让我可以将任何字符串到我自己的AJAX功能 - 例如;

Ideally, I want one method into which I can pass a normal jQuery selector, which will work for selecting titles, divs, or any other element that jQuery can select. This is so that I can pass in any string into my own ajax function - eg;

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

任何帮助将是很大的AP preciated。

Any help would be greatly appreciated.

推荐答案

使用过滤器()与find()方法取决于你的检索HTML页面的结构。例如,如果这是检索页:

The use of filter() vs. find() depends on the structure of your retrieved HTML page. For example, if this is the retrieved page:

<!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>  

如果您要选择顶级元素=元素是身体的直接孩子 - 在这个例子中:#wrap或#tooltip - 那么你必须使用过滤器()

If you want to select the top-level elements = elements that are direct children of BODY - in this example: #wrap or #tooltip - then you have to use filter().

如果您想选择其他元素 - 在这个例子中:的#header,H1,#body,... - 那么你必须使用找到()

If you want to select other elements - in this example: #header, h1, #body, ... - then you have to use find().

我不知道你的元素是身体的一个孩子或没有,你可以使用这个黑客:

I you don't know whether your element is a child of BODY or not, you could use this "hack":

$(&LT; D​​IV&gt;中)HTML(数据).find(选择);

通过使用此解决方法,你总能获得通过元素找到()

By using this work-around, you always get the elements via find().

这篇关于如何过滤来自jQuery.ajax返回的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆