0

i am calling an api for registration and if everything goes well then api returns an xml file

"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\u000a<successNotification>\u000a\u0009<message>Successful web registration<\/message>\u000a\u0009<registrationId>22342347<\/registrationId>\u000a<\/successNotification>"

if something wrong then it returns a line of message

you are missing something

my question is: how can i display message regardless whether it returns xml or just line of message:

$.getJSON('http://localhost:4126/service.svc/alert', { phoneNumber: '01231231233' },
   function (data) {
      var result = $(data).find('message').html;
      display.innerHTML = result;
 });
Nick Kahn
  • 19,652
  • 91
  • 275
  • 406
  • Is the missing `'` for your `phoneNumber` var a typo? – Chris Mar 07 '11 at 19:27
  • To start, your question is missing a single quote. Fix: `{ phoneNumber: '01231231233' }` or `{ phoneNumber: 01231231233 }` (but the second option will interpret the number in octal, which is probably not what you want). – Matt Ball Mar 07 '11 at 19:27
  • 3
    If the API returns an XML file, you probably shouldn't be using "$.getJSON()" ... – Pointy Mar 07 '11 at 19:27
  • @Matt: my question is more towards parsing the xml file i am not sure i understand what you trying to say. – Nick Kahn Mar 07 '11 at 19:33

1 Answers1

0

Use .get, return a string even when you are returning XML and parse it browser side with .parseXML would be one way.

$.get('http://localhost:4126/service.svc/alert', 
   { phoneNumber: '01231231233' },
   function (data) {
      var result;
      if(data.indexOf("<") >= 0) { // test for a character in XML but not the string
          var xmlDoc = $.parseXML(data);
          result = $(xmlDoc).find('message').html();
      } else {
          result = data;
      }
      display.innerHTML = result;
 },
 "text");
justkt
  • 14,610
  • 8
  • 42
  • 62
  • error `Microsoft JScript runtime error: Object doesn't support this property or method` on the line - `$.parseXML(data); ` – Nick Kahn Mar 07 '11 at 20:09
  • @Abu - this is in jQuery 1.5 - what version are you using? – justkt Mar 07 '11 at 20:27
  • @Abu - if you can upgrade to 1.5, do so. Otherwise you will need to use the browser's native methods of converting text to XML. – justkt Mar 07 '11 at 20:33
  • i dont think i will be able to upgrade just because some other developers are using so how is that browser native method of converting to xml – Nick Kahn Mar 07 '11 at 20:35
  • @Abu - see [this StackOverflow question](http://stackoverflow.com/questions/1290321/convert-string-to-xml-document-in-javascript) for a browser native method. It also points out that a well-formed XML string wrapped as a jQuery object can be parsed using jQuery methods, so you should be able to get away with that. – justkt Mar 07 '11 at 20:36