【问题标题】:parse xml response of web service using javascript and ajax使用 javascript 和 ajax 解析 Web 服务的 xml 响应
【发布时间】:2015-07-17 21:36:21
【问题描述】:

我需要用ajax解析web服务返回的xml响应,这是我的代码,'response'是web服务返回的响应,我如何创建一个xml对象并解析它?

$.ajax({
    type: 'POST',
    url: 'web service link',
    dataType: 'xml:lang',
    success: function (response) {
        // how to parse the response here
    },
    error: function (error) {
        console.log(error);
    }
});

这是我的 XML 代码:

<ArrayOfMobileConfiguration xmlns:xsd="w3.org/2001/XMLSchema"; xmlns:xsi="w3.org/2001/XMLSchema-instance"; xmlns="tempuri.org/">; 
    <MobileConfiguration> 
        <Id>1</Id> 
        <Key>STMaxDownloadSize</Key> 
        <Value>132000</Value> 
    </MobileConfiguration> 
    <MobileConfiguration> 
        <Id>2</Id> 
        <Key>ZoomingThresholdValue</Key> 
        <Value>14</Value> 
    </MobileConfiguration>
</ArrayOfMobileConfiguration>

【问题讨论】:

标签: javascript jquery ajax xml web


【解决方案1】:

jQuery 能够以与选择标准 HTML 相同的方式从 XML 响应中检索值。试试这个:

$.ajax({
    type: 'POST',
    url: 'web service link',
    dataType: 'xml',
    success: function (response) {
        $('MobileConfiguration', response).each(function() {
            var id = $(this).find('Id').text();
            var key = $(this).find('Key').text();
            var value = $(this).find('Value').text();

            console.log(id, key, value);
        });
    },
    error: function (error) {
        console.log(error);
    }
});

【讨论】:

  • 我试图执行这段代码,它的工作但如果我将 alert(Id) 放入它显示的函数中:12 和 alert(key) 显示 (STMaxDownloadSizeZoomingThresholdValue) 这意味着 Id 和键是相互连接的xml标签的值,我如何循环每个xml标签并使用该值做一些事情?谢谢你
  • 这段代码在这些元素上循环,所以应该可以正常工作。您最好提出一个新问题,包括您正在使用的代码。
  • 好吧,你是对的,我错了,因为我把 ArrayOfMobileConfiguration 而不是 MobileConfiguration,问候@Rory McCrossan
【解决方案2】:

试试下面的代码,

$.ajax({
type: 'POST',
url: 'web service link',
dataType: 'xml',
success: function (response) {
   $(response).find('MobileConfiguration').each(function(){
        var Id = $(this).find('Id').text();
        var Key = $(this).find('Key').text();
        var Value = $(this).find('Value').text();

        // Use Id, Key, Value according to your requirement.
   });
},
error: function (error) {
    console.log(error);
}
});

【讨论】:

    【解决方案3】:

    这个:

    dataType: 'xml:lang',
    

    应该只是:

    dataType: 'xml',
    

    jQuery 将忽略响应的内容类型并将其解析为 XML,然后在 success 函数中填充您命名为 response 的变量。

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 2017-07-04
      相关资源
      最近更新 更多