views:

311

answers:

3

XML responses from my webapp have both HTML to add to the page AND some have a script to run.

I'm trying to send back XML from my webapp like:

<?xml version="1.0"?>
<doc>
  <html-to-insert>
    <![CDATA[<p>add me to the page</p>]]>
  </html-to-insert>
  <script>
    <![CDATA[ alert('execute me'); ]]>
  </script>
</doc>

What I'm doing now is snapping out the <html-to-insert> and <script> CDATA, inserting the html into the page and eval'ing <script>.

I'm looking for criticism on my approach. Any suggestions from anyone?

A: 

JSON would be a better transport vehicle than XML in this case imho.

code_burgar
A: 

You'd rather send JSON, it's way easier to interpret. Example:

// Suppose your response is a string:
// { html: "<p>add me to the page</p>, script:"alert('execute me');" }
var obj = eval( "(" + response + ")" ) ;
eval( obj.script ) ;
St.Woland
+1  A: 

You can use the jQuery library to make the XML request to your backend and also parse it

$(document).ready(function()
{
  $.ajax({
    type: "GET",
    url: "your/url/that/returns/xml",
    dataType: "xml",
    success: function (xml) {
      // xml contains the returned xml from the backend

      $("body").append($(xml).find("html-to-insert").eq(0));
      eval($(xml).find("script").text());
    }
  });
});

You can find out more about jQuery here and here

I haven't tested it, but it should work according to this article.

Christian Toma