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

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

问题描述

使用jQuery.ajax()方法时,我正努力筛选返回的数据以准确获得所需的信息.我知道使用.load()和其他jQuery AJAX方法很容易,但是我需要专门使用.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.

例如,我知道这可行;

For example I know that this works;

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

任何帮助将不胜感激.

推荐答案

filter()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>  

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

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,...-那么必须使用find().

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

我不知道您的元素是否是<body>的子元素,您可以使用此"hack":

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

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

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

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

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

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