ajax - 使用 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 标签中的数据?使用这些标签时,我的代码似乎不起作用。任何帮助都会很棒。
解决方案
解决方案
您必须将 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');
// ...
参考
推荐阅读
- segmentation-fault - Caffe 训练错误:分段错误(核心转储)
- monitoring - 如何从普罗米修斯获取昨天的总 nginx 请求?
- php - 从 MYSQL 中随机选择元素
- java - 使用 CrudRepository 仅提取某些字段?
- webpack - 如何使用 webpack 在块之间共享单例实例?
- php - .php 脚本的文件夹和文件
- python - 如何将json文件的路径保存为原始字符串
- php - 为 WordPress 生成随机数以供人工检查
- python - Tensorflow MultiRNNCell LSTM:“‘张量’对象不可迭代”
- arrays - 使用条件对数组进行洗牌