[英]jquery, ajax call inside a function: can't access a global variable passed as argument to outer function from ajax success
I have a function with two parameters that I need to correctly make an ajax call and process the results, as this function is called two times and with different arguments.
我想要完成的是用從 Ajax 調用中獲得的數據覆蓋全局變量myArray
。
const api_url = 'some-url';
const api-key = 'some-key';
var myArray = [];
function doThis(endpoint, array) {
$.ajax({
'url': api_url + endpoint,
'method': 'get',
'data': {
'api_key': api_key,
},
'success': function(data) {
/*store data in global variable for later use*/
array = data.keyname;
},
'error': function() {
console.log('ajax error');
},
});
}
doThis(someEndpoint, myArray);
What the rest of the success function (not included) does is it uses the Handlebars.js library to print a few options in a select, so once that's been drawn correctly I am 100% sure that the Ajax call has returned.
我的印象是傳遞一個空數組作為參數將允許我使用 function 中的參數對空數組本身進行操作。 但是,如果即使在繪制 select 之后我嘗試console.log(myArray)
,我仍然會留下一個空數組,我無法弄清楚為什么,因為分配發生在成功 function 中,一旦調用觸發就會觸發返回,所以這不應該是異步的問題。
我還嘗試在 ajax 調用和外部 function 的末尾使用return array
,但這仍然沒有效果。
Eta: data.keyname
返回一個對象數組。
我懷疑您假設將值作為新數組分配給 function 內的參數將更新傳遞給 function 的變量的值。 不是這種情況。
而是將新數據推送到參數表示的數組引用中
簡化示例:
let myarr = []; function doStuff(arr) { arr = [1, 2, 3];// your approach that doesn't work } doStuff(myarr); console.log('After doStuff', myarr) function doStuff2(arr) { arr.push(...[1, 2, 3]);// update the array object instead } doStuff2(myarr); console.log('After doStuff2', myarr)
更現代的方法是返回 $.ajax promise
var myArray = [];
function doThis(endpoint) {
return $.getJSON(api_url + endpoint, {api_key: api_key});
}
doThis(someEndpoint).then(data=>{
// do stuff with data and also store in global
myArray = data.keyname
});
data.keyname
有一些有效的東西array
現在指向新的 object 並且myArray
仍然位於[]
。 您可以傳遞一個 object ,其一個屬性是一個數組,對象的數組鍵將指向您可以訪問的新數組 - console.log(myObject.array);
這也需要在 Ajax 完成后完成,因為 ajax 調用異步 functionconst api_url = 'some-url';
const api-key = 'some-key';
var myObject = {array:[]};
function doThis(endpoint, obj) {
$.ajax({
'url': api_url + endpoint,
'method': 'get',
'data': {
'api_key': api_key,
},
'success': function(data) {
/*store data in global variable for later use*/
obj.array = data.keyname;
success();
},
'error': function() {
console.log('ajax error');
},
});
}
doThis(someEndpoint, myObject);
function success(){
console.log(myObject.array);
}
您沒有正確使用 Array。 Ajax 應返回 json 中的數據,您將其存儲在某個變量中。 然后您再次解析並轉換為數組,以防您需要它作為數組。 所以你應該在成功聲明中使用 JSON.parse(data.keyname) 。 我假設數據以 json 格式出現。 在此處了解有關 JSON.parse 的更多信息https://www.w3schools.com/js/js_json_parse.asp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.