After creating a .net web api method, I encountered an issue where the XML response returned when the API is opened in a browser appears valid (http://localhost:49546/api/Products)
<ArrayOfProductModel><ProductModel><Color>Black</Color><DiscontinuedDate i:nil="true"/><ListPrice>1431.5000</ListPrice><ModifiedDate>2008-03-11T10:01:36.827</ModifiedDate><Name>HL Road Frame - Black, 58</Name><ProductCategoryId>18</ProductCategoryId><ProductId>680</ProductId><ProductModelId>6</ProductModelId><ProductNumber>FR-R92B-58</ProductNumber><SellEndDate i:nil="true"/><SellStartDate>2002-06-01T00:00:00</SellStartDate><Size>58</Size><StandardCost>1059.3100</StandardCost><Weight>1016.04</Weight></ProductModel> </ArrayOfProductModel>
However, when attempting to call this method using AJAX, the data
displays as an [object XMLDocument]
. Unfortunately, data.responseXML
is undefined, preventing me from processing the XML response to display it as a table.
<script type="text/javascript">
$(document).ready(function () {
getProducts();
});
function getProducts()
{
$.ajax({
url: 'http://localhost:49546/api/Products',
method: 'GET',
dataType: 'xml',
//contentType: 'application/xml; charset=utf-8',
success: function (data) {
alert("GetProducts successfully");
showProducts(data);
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
})
}
function showProducts(data)
{
alert(data);
alert(data.responseXML);
alert(data.responseText);
var i;
var xmlDoc = data.responseXML;
var table = "<tr><th>Nombre</th><th>ListPrice</th></tr>";
var x = xmlDoc.getElementsByTagName("ProductModel");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("ListPrice")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("prodTable").innerHTML = table;
}
</script>
If you have any insights on what might be missing or incorrect in my setup, please let me know.