Reputation: 199
I have a jquery function which communicates with an ASP.NET web service which looks like this
$(document).ready(function() {
$.support.cors = true;
$.ajax({
type: "GET",
url: "http://www.webservice.com/blahblah.asmx/blahb123",
data: "tnWsGuid=TEST1",
dataType: "text",
success: function(data, status, jqxhr) {
xmlString = data;
alert(xmlString);
},
error: function (request, status, error) {
alert(status);
}
});
});
Alert display's this:
<?xml version="1.0" encoding = "utf-8"?>
<string xmlns = "http://Walkthrough/XmlWebServices/">
{"approverName":"","emailAddress":"","companyName":"ABC","address":{"streetAddress1":"12 BlahBlah","streetAddress2":"","state":"ON","zipCode":"","country":"SO","phoneNumber":""},"tabledata:"[{"vendorPart":"AAAAA","partDescription":"N/A","price":"0.00","quantity":"28"},{"vendorPart":"BBBBBBB","partDescription":"N/A","price":"0.00","quantity":"3"},{"vendorPart":"CCCCCC","partDescription":"N/A","price":"0.00","quantity":"25"}]}
</string>
My dataType is now text. I know how to parse JSON however, now what I need to do is somehow access the JSON embedded in the XML envelope and turn it into a JSON object so I can use JQuery to parse it.
Here is what I have tried in the $.ajax function:
success: function(data, status, jqxhr) {
xmlString = data;
var jsondata = jQuery.parseJSON(xmlString.substr(xmlString.indexOf('{')));
alert(jsondata);
}
But was returned with an error of Invalid character which in the IE debugger look's like this
Any idea how I can access the data inside the xml envelope and turn it into a JSON object so I can parse it as JSON? I do not have the ability to change the web service so this must all be done within the web page.
Upvotes: 1
Views: 1632
Reputation: 28114
As your call is returning xml, you could use dataType:"xml"
instead of "text".
You can then process the xml response:
var jsonData=$.parseJSON(data.find("string").text());
Upvotes: 1
Reputation: 49919
You can do this:
success: function(data, status, jqxhr) {
var xml = $($.parseXML(data)), // Parse the XML String to a Document, and Wrap jQuery
json = xml.find("string").text(), // Get the text of the XML
jsonObj = $.parseJSON(json); // Parse the JSON String
}
Or short notation
var jsonObj = $.parseJSON($($.parseXML(data)).find("string").text());
Live Fiddle: http://jsfiddle.net/59rQA/
Upvotes: 1
Reputation:
I think your substring is adding the closing tag for to the JSON data. How about:
xmlString = $.parseXML(xmlString);
var jsondata = $.parseJSON($(xmlString).children('string').text());
Upvotes: 1