Martin
Martin

Reputation: 10563

jQuery how to get body contents out of html reponse

I have a bit of a problem.

I have an ajax request that is sent out to do a database update. A response is then returned that looks like:

...
...
</head>
<body class="contentpane">
{"id":"27","votes":14,"sum":45,"avg":"3.2"}
</body>
</html>

How can I get the contents of body class "contentpane" and then convert this to a JSON object?

My request function looks like this:

  jQuery.post("index.php?option=com_ttvideo&task=savevote&tmpl=component", {rate: value, id: <?php echo $this->video->id; ?> }, function(html)
  {
    // get contents of "contentpane" from response html
    // convert to JSON object e.g.
    // var rating = jQuery.parseJSON(content_of_body);    
    // is the above JSON parse correct?    

    // Select stars to match "Average" value
    ui.select(Math.round(rating.avg));

    // Update other text controls...
    jQuery("#avg").text(rating.avg);
    jQuery("#votes").text(rating.votes);

    // Show Stars
    jQuery("#loader").hide();
    jQuery("#rat").show();

  });

Upvotes: 1

Views: 7423

Answers (2)

user1709374
user1709374

Reputation: 939

Pretty easy. Wrap inner of BODY by DIV will do:

$.get(url, {}, function(data){
  var data = data.replace('<body', '<body><div id="body"').replace('</body>','</div></body>');
  var body = $(data).filter('#body');
  (... do what you want with body ...)
});

Upvotes: 4

SLaks
SLaks

Reputation: 887415

Like this:

$.parseJSON($('body', html).text())

I'm assuming, perhaps incorrectly, that the JSON will be HTML escaped. If it isn't, you will sometimes be able to call .html() instead of .text(), but will more likely need to write your own parser.

You should replace your webservice with a real JSON response.

Upvotes: 1

Related Questions