whatyouhide
whatyouhide

Reputation: 16781

AJAX returned data - how to treat them with jQuery

So when jQuery makes an $.ajax request, the returned data can be handled with the success function attribute (a function) of the object passed as a parameters to $.ajax. As the API docs report, if the processData attribute is set to true, the data will be returned as a string, otherwise as a DOM object (is that right?).

So, I need to treat the data as if they were simple HTML. Let's say I have to prepend and append a series of =s to every h1 tag in the returned data, and then fill a page with those data as if they were a plain string (in order to use the jQuery .html() method).

What's the correct way to do it?

I found that the .parseHTML() jQuery function could be useful in order to parse the returned data string into HTML DOM. But how do I treat it?

Sorry for some lack of what have you tried in this question.

Edit

Someone suggested a more clear example. I have a .html file with some content I want to retrieve through AJAX and use to fill my main page content. This file is structured as simple HTML, without head/body tags, just some ps and a few h1s. Through CSS I already made h1 tags look exactly like ps (which is intended). Now I want to transform this:

<h1>I'm a simple header</h1>

into plain text this:

===================
I'm a simple header
===================

kind of Unix terminal style.

Upvotes: 0

Views: 264

Answers (1)

What have you tried
What have you tried

Reputation: 11148

EDIT The below is working perfectly for me

File1.html

<script type="text/javascript">
$(document).ready(function(){
$.ajax({  
    url: 'http://voicing-up.com/test.html',  
        success: function(data) {  
                alert(data);
            alert($(data).html());
        }  
    });
});
</script>

Test.html

<p>This is some data</p>
<h2>This is h2</h2

In the code above, data is going to return DOM elements, and from there you can use jQuery's .html() function to get the innerHTML of the element.

Upvotes: 1

Related Questions