Alex Rivera | Logout

Using JSONP when returning XML

Asked 2010-08-08T18:09:52.847
13

I asked an earlier question which was definitely helpful and let me know about JSONP. However, I see that I have to specify JSONP as the datatype. Now, as far as I know, that is the return type of the data coming back, which would be XML. Can XML be returned using JSONP or am I limited to it coming back as JSONP format? Thanks!

Edit
Report

1 Answer

2

The idea is to send back executable code from the server. Write a jQuery plugin or extend the ajax function to return the XML string as a function parameter.

myCallback("
  <root>
    <person>
      <first>John</first>
      <last>Doe</last>
    </person>
  </root>")

The plugin will parse this string to XML and return it back to your actual callback. As far as your callback is concerned, it is unaware of the string -> xml conversion process.

Here's an existing implementation.

The most ideal interface to this with jQuery would be,

$.ajax({
    url: 'http://example.com/resource?type=xml',
    dataType: 'xmlp',
    success: function(xml) { .. }
});

but since messing around and rewriting jQuery.ajax is problematic, you could write this as a separate namespaced plugin itself which will use getScript underneath.

$.myNamespace.ajax({
    ..
});

For this to work, you would need control of the server. The server has to know that XML is requested, and respond with a function call which contains the XML string as a parameter. Assuming the callback name you sent over to the remote server was foo, the server will have to respond with something like:

foo("<names><name>..</name></names>")

I think if you were using a browser that supported E4X, then there would be no need to wrap the XML inside a string. The server could simply return the XML as an argument to the callback function:

foo(
  <names>
    <name>John Doe</name>
  </names>
)

But unfortunately, E4X is not widely supported yet.

answered 2010-08-08T18:32:03.817

Your Answer