首页 > 解决方案 > 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 方法中添加一个参数?

标签: javascriptjqueryajax

解决方案


也许您可以尝试使用 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
    });
};


推荐阅读