2017-10-08 35 views
1

使用Office的JavaScript API,我嘗試使用下面的代碼填寫所選表:的MS Word 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")。

如何告訴Word讓我將表變量保留一段時間,因爲一旦我的Ajax完成,我將更新其內容?

回答

1

發生這種情況的原因是,您的功能繼續(並完成),而您的$.ajax()調用發生在後臺。你需要阻止執行,而你的ajax()調用不是事情。

你可以這樣做一對夫婦的方式,但最簡單的可能是簡單地設置您的ajax()選項async: false

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

此外,您還需要通過第二個參數(稱爲insertLocation;要插入文本)至body.insertText:或者'Replace''Start''End'