0

I have a .net web api method that when open in the browser it returns a valid XML (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>

When I try to call that method using AJAX the data is being shown as an [object XMLDocument] but the data.responseXML is undefined so I can not process the XML response to show 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>";
        }
        //alert(data);
        document.getElementById("prodTable").innerHTML = table;
    }
</script>

Please let me know what is missing or wrong

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99

1 Answers1

0

Web API passes back JSON as the default data type. That's what you're getting in {"location":null}

If you want to pass back XML, check out this article: WebAPI to Return XML

Community
  • 1
  • 1
nixkuroi
  • 2,259
  • 1
  • 19
  • 25