将XML解析为String,从服务器返回XML

时间:2017-01-13 14:47:37

标签: jquery xml

所以我目前有以下代码:

<script>
    var params = {};
    var results = '';
    params["companyID"] = <%=company.getId()%>
    $.ajax({
        url: "services/contacts/<%=ContactServices.Action.GET_CONTACT_LIST%>",
        data: params,
        complete: function(xhr) {
            results = xhr;
            console.log(results);
            var booboo = $.parseXML(results);
            console.log(booboo);
        }
    });
</script>

并且结果返回以下responseText:

 "<?xml version="1.0" encoding="ISO-8859-1"?><Response>[Fara Hussain,
 Default Contact, Gogo Hussain, Emma Lowdon, John
 Stewart]<Success/></Response>"

我目前对仅在括号中的项目感兴趣:

  

Fara Hussain,默认联系人,Gogo Hussain,Emma Lowdon,John Stewart

然后我尝试解析XML。但是,当我尝试解析XML时,它返回null。

var booboo = $.parseXML(results);
console.log(booboo);

任何想法如何克服这个?

1 个答案:

答案 0 :(得分:0)

jqXHR不是来自服务器的响应。您需要解析响应而不是ajax对象本身。

complete: function(xhr) {
        results = xhr.responseXML || xhr.responseText;
        console.log(results);
        var booboo = $.parseXML(results);
        console.log(booboo);
    }

这是一个巧妙的技巧,只需将这些东西放在括号中:

&#13;
&#13;
var results = "<Response>[Mubean Hussain, Default Contact, Mubean Hussain, Emma Harding, John Stewart]<Success/></Response>";
var text = $("<div>").html(results).text();
// text will now contain just the stuff in the brackets
console.log(text);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

这可以通过创建一个未添加到DOM的虚拟div,将xml作为html插入然后获取忽略任何标记的div的textContent来实现。