javascript - Ajax 方法,未定义变量,两种可能的解决方案?
问题描述
抱歉这个简单的问题,我是 Javascript 和 Ajax 的新手。这是我的代码:
var rootURL = "http://localhost:8080/WineCellar/rest/wines";
var findById= function(id){
var testWine;
console.log('findById: ' + id);
$.ajax({
type: 'GET',
url: rootURL + '/' + id,
dataType: 'json',
success: function(data){
console.log('findById success: '+ data.name);
testWine = data;
}
});
return testWine;
};
var myWine = findById(3);
console.log(myWine.name);
它提供以下控制台输出: https ://i.stack.imgur.com/JqmHQ.png
无法读取未定义的属性“名称”
myWine 未定义。我该如何解决?是否有可能有两种方法来克服这个问题?也许我需要在 ajax 方法中添加一个参数?
解决方案
也许您可以尝试使用 fetch API ( https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API ) 这里有一个例子
let YOUR_API = "https://swapi.dev/api/people/1/";
let cache;
window.onload = function () {
fetch(YOUR_API)
.then((response) => response.json())
.then((myJsonResponse) => {
cache = myJsonResponse;
console.log(cache);
// the rest of the code that runs on this response
});
};
推荐阅读
- hadoop - 使用 API 在 Hadoop 中移动文件
- javascript - 相互作用。页面加载时的 Blast.js 动画
- apache-spark-sql - 在 hdfs 中写入小文件或使用 coalesce
- amazon-web-services - AWS Glue,将 CSV 传输到 Redshift
- sql - 在 MS Access VBA 中使用 Like 运算符和通配符
- php - Laravel 在队列上创建作业
- c# - .net Interop.Word 从 docx 插入而不搞砸格式
- android - 在 Android P 上创建设置活动
- javascript - 如何在每个用户操作上运行一个函数?
- oracle12c - Oracle 12c 连接系统时不检查密码