Javascript 调用Ajax导出函数返回值
当我用返回的Javascript 调用Ajax导出函数返回值,javascript,jquery,ajax,asynchronous,Javascript,Jquery,Ajax,Asynchronous,当我用返回的 export function getChampion(id, country) { $.ajax({ type: "GET", url: `http://ddragon.leagueoflegends.com/cdn/9.24.2/data/${country}/champion.json`, dataType: "json", success: function(data) { c
export function getChampion(id, country) {
$.ajax({
type: "GET",
url: `http://ddragon.leagueoflegends.com/cdn/9.24.2/data/${country}/champion.json`,
dataType: "json",
success: function(data) {
console.log(data);
idToChampion(data, id);
}
});
}
// Return the ChampionId
function idToChampion(data, theId) {
let resultObject = search(theId, data);
console.log(resultObject);
return resultObject.id;
}
function search(key, inputArray) {
inputArray = Object.values(inputArray.data)
for (let i = 0; i < inputArray.length; i++) {
if (inputArray[i].key === key) {
return inputArray[i];
}
}
}
导出功能getChampion(id,国家){
$.ajax({
键入:“获取”,
网址:`http://ddragon.leagueoflegends.com/cdn/9.24.2/data/${country}/champion.json`,
数据类型:“json”,
成功:功能(数据){
控制台日志(数据);
idToChampion(数据,id);
}
});
}
//返回ChampionId
函数idToChampion(数据,theId){
让resultObject=search(theId,data);
console.log(resultObject);
返回resultObject.id;
}
函数搜索(键、输入阵列){
inputArray=Object.values(inputArray.data)
for(设i=0;i
函数“getChampion”返回未定义,我不明白为什么以及如何修复它。提前感谢如果您不想让它返回未定义的,您可以使用承诺使其成为异步函数
export function getChampion(id, country) {
return new Promise(resolve => {
$.ajax({
type: "GET",
url: `http://ddragon.leagueoflegends.com/cdn/9.24.2/data/${country}/champion.json`,
dataType: "json",
success: function(data) {
resolve(data)
}
});
})
}
然后你可以使用
let data = await getChampion(id, country);
...
您的
getChampion
函数不返回任何值
假设您希望根据冠军的id获取冠军数据,您可以尝试以下功能:
异步函数getChampion({id,lang=“en_US”}){
const{data}=await$.getJSON(`http://ddragon.leagueoflegends.com/cdn/9.24.2/data/${lang}/champion.json`).promise()
返回数据[id]
}
以下是如何称呼它:
(异步()=>{
日志(等待getChampion(“Aatrox”))
//=>{“头衔”:“黑暗之刃”,“宣传语”:“曾经是舒里玛抵抗虚空的光荣捍卫者,阿特洛克斯和他的兄弟们最终将成为鲁奈特拉更大的威胁,并且只被狡猾的凡间巫术打败。但在数个世纪的监禁之后,阿特洛克斯是第一个发现……”,…}
日志(等待getChampion(“Ahri”))
//=>{“标题”:“九尾狐”,“模糊”:“天生与Runeterra的潜在力量有关,Ahri是一个可以将魔法重塑为原始能量球体的vastaya。她在吞噬猎物生命本质之前,通过操纵猎物的情绪来玩弄猎物。尽管她具有掠夺性的天性……”
})()
您还可以使用promise界面:
getChampion(“Aatrox”)。然后(console.log)
//=>{“头衔”:“黑暗之刃”,“宣传语”:“曾经是舒里玛抵抗虚空的光荣捍卫者,阿特洛克斯和他的兄弟们最终将成为鲁奈特拉更大的威胁,并且只被狡猾的凡间巫术打败。但在数个世纪的监禁之后,阿特洛克斯是第一个发现……”,…}
getChampion(“Ahri”)。然后(console.log)
//=>{“标题”:“九尾狐”,“模糊”:“天生与Runeterra的潜在力量有关,Ahri是一个可以将魔法重塑为原始能量球体的vastaya。她在吞噬猎物生命本质之前,通过操纵猎物的情绪来玩弄猎物。尽管她具有掠夺性的天性……”
在getChampion
中没有return
语句-因此它根据javascript语言的规范返回未定义的
-具有讽刺意味的是,您的idToChampion
函数返回一个您甚至没有返回的值use@JaromandaX当我在“getChampion”中添加回报时我也没有定义。取决于你在哪里添加它return$.ajax….
?@JaromandaX我在“success:function(data)…
中尝试过,在ajax调用之后,这是一个clalback,因此返回那里没有任何作用