使用AJAX从Google Sheet XML文件中提取数据



我对处理Google Sheet中的XML文件相对陌生,并且有一个从Google Sheet生成的XML文件,我想从中获取数据并将其显示在表中。Google Sheets生成的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标记中的数据?当使用这些标记时,我的代码似乎不起作用。任何帮助都会很棒。

解决方案

您必须将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');
// ...

参考

DOMParser

最新更新