Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

How do I filter the returned data from 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...