gpt4 book ai didi

javascript - MS Word API : Set table values loaded async

转载 作者:行者123 更新时间:2023-11-30 21:05:45 24 4
gpt4 key购买 nike

使用 Office JavaScript API,我尝试使用以下代码填充选定的表格:

Word.run(function (context) {

var table = context.document.getSelection().parentTable;
table.load("values, rows/items/cells/items/body");
context.trackedObjects.add(table);

return context.sync().then(function () {
// loop over table
for (var row = 0; row < table.values.length; row++) {
for (var column = 0; column < table.values[row].length; column++) {
// use closures to keep cell index variables for ajax
(function (row, column, table, context) {
if ((table.values[row][column].trim() ==
"" || !table.values[row][column]) &&
table.values[row][0] && table.values[0][column]) {

$.ajax({
url: "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/" +
table.values[row][0].replace(/\s/g, '') +
"/property/" + table.values[0][column] + "/txt"
}).done(function (data) {

// insert data
table.rows.items[row].cells.items[column].body.insertText(data);
console.log("data: " + data);

return context.sync().then(function () {
console.log("synced");
}).catch(function (e) {
console.log("0");
errorHandler(e);
});

}).error(function (e) {
console.log("1");
errorHandler(e);
});
} else {
console.log(row + " " + column + " not beeing set, it is " +
table.values[row][column]);
}
})(row, column, table, context);
}
}
}).then(context.sync().then(
function () {
console.log("last sync?");
}
).catch(function (e) {
console.log("2");
errorHandler(e);
}));
}).catch(function (e) {
console.log("3");
errorHandler(e);
});

但不知何故,这不起作用,因为会抛出异常:

ItemNotFound: ItemNotFound

错误的来源是 - 根据日志 (0) 和插入数据处的错误 ("errorLocation":"TableRowCollection.getItem")部分。

我将在 Ajax 完成后立即更新其内容,因此如何告诉 Word 让我将表变量保留更长的时间?

最佳答案

发生这种情况的原因是您的函数继续(并完成)而您的 $.ajax() 调用在后台发生。您需要阻止执行,而您的 ajax() 调用不是问题。

你可以通过几种方式来做到这一点,但最简单的可能是简单地在你的 ajax() 选项中设置 async: false:

$.ajax({
url: "https://pubchem.ncbi.nlm.nih....",
async: false
}).done(function (data) {});

此外,您还需要将第二个参数(称为 insertLocation;您要插入文本的位置)传递给 body.insertText : 'Replace''Start''End'

关于javascript - MS Word API : Set table values loaded async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46631501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com