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

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

问题描述

当使用 jQuery.ajax() 方法时,我正在努力过滤返回的数据以获得我需要的数据.我知道这很容易使用 .load() 和其他 jQuery AJAX 方法,但我需要专门使用 .ajax().

例如我知道这行得通;

var title = $(data).filter('title');//返回页面标题

但是如果我只想要 id="foo" 的 div 的内容怎么办?

var foo = $(data).filter('#foo');//这些都不起作用var foo = $(data).find('#foo');//var foo = $('#foo', 数据);//

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

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

任何帮助将不胜感激.

解决方案

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

<头><title>Foo</title><身体><div id="包裹"><div id="标题"><h1>Foo</h1>

<div id="body">内容

<div id="工具提示">工具提示

如果要选择顶级元素 = 的直接子元素 - 在本例中:#wrap#工具提示 - 那么你必须使用filter().

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

, #body, ...- 那么你必须使用 find().

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

$("

").html(data).find(选择器);

通过使用这种变通方法,您始终可以通过 find() 获取元素.

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

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);        //

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

Any help would be greatly appreciated.

解决方案

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>  

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

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":

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

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

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

查看全文

相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆