weixin_33720452 2015-01-23 16:21 采纳率: 0%
浏览 31

消耗XML-消息未定义

I'm trying to consume XML Web Service but I'm getting result.Message undefined in success function. Whats wrong in this code? The error is:

Uncaught TypeError: Cannot read property 'Message' of undefined

Here is my code:

function RequestService() {
    $.ajax({
        type: "GET",
        url: "http://www.brazilmachinery.com/Arquivos/RSS/pt-BR/12.xml",
        data: "",
        dataType: "xml",
        success: function(data) { SucessCallback(data.d); },
        error: function(data) { FailureCallBack(data); }
    });
}

function SucessCallback(result) {
    $('p').html('Resultado: ' + result.Message + ' <br /> Descrição: ' + result.Description);
}

function FailureCallBack(result) {
    alert("erro");
}
  • 写回答

2条回答 默认 最新

  • 普通网友 2015-01-23 16:44
    关注

    Your response is an XML file. You are assuming it returns JSON object and trying to access a property.

    You will have to parse the XML file and extract the node you want to retrieve. Below is a XML to JSON utility function. You can use this to access the property.

    function xmlToJson(xml) {   
        // Create the return object
        var obj = {};
    
    if (xml.nodeType == 1) { // element
        // do attributes
        if (xml.attributes.length > 0) {
        obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) { // text
        obj = xml.nodeValue;
    }
    
    // do children
    if (xml.hasChildNodes()) {
        for(var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof(obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof(obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
        }
        return obj;
    };
    

    Source: http://davidwalsh.name/convert-xml-json

    评论

报告相同问题?