首页 > 解决方案 > 使用 AJAX 从 Google Sheet XML 文件中提取数据

问题描述

我对处理来自 Google Sheets 的 XML 文件相对较新,并且有一个从 Google Sheet 生成的 XML 文件,我想从中获取数据并将其显示在表格中。Google 表格生成的 XML 文件显示每个条目,如下所示:

<entry>
    <id>https://spreadsheets.google.com/feeds/list<MyID>/2/public/values/cokwr</id>
    <updated>2020-09-08T10:27:43.003Z</updated>
    <category scheme='http://schemas.google.com/spreadsheets/2006' term='http://schemas.google.com/spreadsheets/2006#list'/>
    <title type='text'>1</title>
    <content type='text'>name: Joe Bloggs, totalpoints: 0</content>
    <link rel='self' type='application/atom+xml' href='https://spreadsheets.google.com/feeds/list/<MyID>/2/public/values/cokwr'/>
    <gsx:pos>1</gsx:pos>
    <gsx:name>Joe Bloggs</gsx:name>
    <gsx:totalpoints>0</gsx:totalpoints>
</entry>

我的 html 文件如下所示:

<body>
  <table id = "league_data">
  <tr><th>Pos</th><th>Name</th><th>Points</th>
  </tr>
  </table>

  <script>
     $(document).ready(function(){
           $.ajax({
               type: "GET",
               url: "https://spreadsheets.google.com/feeds/list/<MyID>/2/public/values",
               dataType: "html",
               success: function(xml){
                 console.log("here");$
                   $(xml).find('entry').each(function(){
                       var Pos = $(this).find('gsx:name').text();
                       var Name = $(this).find('gsx:name').text();
                       var Points = $(this).find('gsx:totalpoints').text();
                       $('<tr></tr>').html('<th>' +Pos+ '</th><td>$' +Name+ '</td><td>$' +Points+ '</td>').appendTo('#league_data');
                   });
               }
           });
   });
  </script>

</body>

是否可以检索包装在 gsx:pos、gsx:name 和 gsx:totalpoints 标签中的数据?使用这些标签时,我的代码似乎不起作用。任何帮助都会很棒。

标签: ajaxxmlgoogle-sheetsget

解决方案


解决方案

您必须将 XML 解析为 DOM 才能访问这样的标签名称。

这是您没有 JQuery 的情况的示例:

// inside the success callback
const parser = new DOMParser();
let xmlDom = parser.parseFromString(xml, 'text/xml');
let Pos = xmlDom.getElementsByTagName('gsx:pos')[0].textContent;
let Name = xmlDom.getElementsByTagName('gsx:name')[0].textContent;
let Points = xmlDom.getElementsByTagName('gsx:totalPoints')[0].textContent;
$('<tr></tr>').html('<th>' +Pos+ '</th><td>$' +Name+ '</td><td>$' +Points+ '</td>').appendTo('#league_data');
// ...

参考

DOM解析器


推荐阅读