![](/img/trans.png)
[英]Angular.js: Storing variable from http.get request to use globally in different $scope function
[英]Return info from JS array to use as a variable globally
第一次在這里發布,希望有人可以幫助我。
我仍在學習JS,對語言不了解很多,我已經做了一些Google搜索,但是找不到解決方案
如果這是一個非常愚蠢的問題或之前已經回答過,我會提前道歉
這是從Google表格文檔中獲取信息並將其放入數組的代碼(感謝@ Z-Bone)
var spreadsheetUrl ='https://spreadsheets.google.com/feeds/cells/1XivObxhVmENcxB8efmnsXQ2srHQCG5gWh2dFYxZ7eLA/1/public/values?alt=json-in-script&callback=doData';
var mainArray =[]
// The callback function the JSONP request will execute to load data from API
function doData(data) {
// Final results will be stored here
var results = [];
// Get all entries from spreadsheet
var entries = data.feed.entry;
// Set initial previous row, so we can check if the data in the current cell is
from a new row
var previousRow = 0;
// Iterate all entries in the spreadsheet
for (var i = 0; i < entries.length; i++) {
// check what was the latest row we added to our result array, then load it
to local variable
var latestRow = results[results.length - 1];
// get current cell
var cell = entries[i];
// get text from current cell
var text = cell.content.$t;
// get the current row
var row = cell.gs$cell.row;
// Determine if the current cell is in the latestRow or is a new row
if (row > previousRow) {
// this is a new row, create new array for this row
var newRow = [];
// add the cell text to this new row array
newRow.push(text);
// store the new row array in the final results array
results.push(newRow);
// Increment the previous row, since we added a new row to the final
results array
previousRow++;
} else {
// This cell is in an existing row we already added to the results
array, add text to this existing row
latestRow.push(text);
}
}
handleResults(results);
}
// Do what ever you please with the final array
function handleResults(spreadsheetArray) {
console.log(spreadsheetArray);
}
// Create JSONP Request to Google Docs API, then execute the callback function
doData
$.ajax({
url: spreadsheetUrl,
jsonp: 'doData',
dataType: 'jsonp'
});
從這里開始,我想將所有數組項都聲明為變量,以便可以在全局站點上的任何其他函數中使用它們中的任何一個,或從任何函數將其寫入innerHTML中。
如果將它們聲明為變量不是正確的解決方案,請隨意提出其他建議,就像我在JS初學者中所說的那樣
預先感謝您的幫助Stack Overflow Family
將要全局設置的變量存儲為window
的屬性:
function handleResults(spreadsheetArray) {
window.spreadsheetArray = spreadsheetArray;
}
去測試:
handleResults([1,2,3]);
(function printArray() {
console.log(window.spreadsheetArray);
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.