Reputation: 101
I've been dabbling in PageMethods (in Webfroms) for a Web App I'm developing. I hit a wall when it came to master pages (ie. PageMethods coming back 'undefined'). So, I've changed my approach and am looking at calling a method inside a Web Service instead. (There seems to be a few advantages over PageMethods as well.)
I'm having a bit of difficulty when it comes to getting array information back from the C# code inside the Web Service into Javascript (so it can be used on the client side). The code in the web service (for concept testing) is:
[WebMethod]
public int[] HelloWorld()
{
return new int[] { 1, 2, 3};
}
The Javascript calling the C# method inside the Web Service is:
function processSourceInputButtonClicked() {
$.ajax({
type: "POST",
url: "Webservice.asmx/HelloWorld",
data: "{}",
dataType: "text",
success: function (data) {
alert("Ok:" + data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Err:" + textStatus + "," + errorThrown.toString());
}
});
};
If I look at 'data', the array comes back as a bunch of XML:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<int>1</int>
<int>2</int>
<int>3</int>
</ArrayOfInt>
Is there a way of converting this HTML into a Javascript array of integers?
Upvotes: 3
Views: 665
Reputation: 33306
First you need to parse the xml and find the int nodes.
Then you can iterate over the collection and do as you wish.
Here is a simple example that adds the values to an unordered list:
var xml = '<?xml version="1.0" encoding="utf-8"?><ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/"><int>1</int><int>2</int> <int>3</int></ArrayOfInt>';
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$ints = $xml.find( "int" );
$.each($ints, function( index, value ) {
$( "ul" ).append('<li>' + $(value).text() + '</li>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul></ul>
Upvotes: 1
Reputation: 1490
You should change the "dataType" to "json" like this:
$.ajax({
type: "POST",
url: "Webservice.asmx/HelloWorld",
data: "{}",
dataType: "json", // change "text" to "json"
success: function (data) {
alert("Ok:" + data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Err:" + textStatus + "," + errorThrown.toString());
}
});
Upvotes: 1