Jquery 如何一次从API获取数据,然后多次使用该数据?
我有一个函数,它通过JQuery的$.post()方法发出post请求,并从API检索客户列表。我必须在下拉列表中加载此客户列表,以便用户选择一个。然后,用户将有可能在客户端上添加另一个下拉列表,该列表必须填充以前从API获取的相同数据Jquery 如何一次从API获取数据,然后多次使用该数据?,jquery,ajax,asynchronous,Jquery,Ajax,Asynchronous,我有一个函数,它通过JQuery的$.post()方法发出post请求,并从API检索客户列表。我必须在下拉列表中加载此客户列表,以便用户选择一个。然后,用户将有可能在客户端上添加另一个下拉列表,该列表必须填充以前从API获取的相同数据 function fillCustomerList(selector) { let req = { "api_uid": /*myapiuid*/, "api_key": /*myapikey*/
function fillCustomerList(selector) {
let req =
{
"api_uid": /*myapiuid*/,
"api_key": /*myapikey*/
};
req = JSON.stringify(req);
$.post("https://api.fattureincloud.it:443/v1/clienti/lista", req, "json")
.done(function (data) {
var customerList = data["lista_clienti"];
//fill first product list with products
for (let i = 0; i < customerList.length; i++) {
$(selector+" .customerList").append("<li class='list-group-item'>" + customerList[i]["nome"] + "</li>");
}
}).fail(function () {
//TODO show error message
console.log("getCustomerList error");
});
var customerList = data["lista_clienti"];
//fill first product list with products
for (let i = 0; i < customerList.length; i++) {
$(selector + " .customerList").append("<li class='list-group-item'>" + customerList[i]["nome"] + "</li>");
}
}
因为请求是异步的,所以当我尝试访问列表时,它仍然是空的
我找到的唯一解决方案是,每当用户想要生成新的下拉列表时,从API重新获取数据,我认为这不好,因为我对服务的API调用数量有限制
有没有一种方法可以让我只需要发出一次请求?或者我必须通过许多不同的请求检索相同的数据吗?请显示您的代码将第一个Ajax调用结果保存到一个变量中。然后在创建另一个下拉列表时,使用保存的结果生成下拉列表的选项。但问题是,我只能安全地(即确保变量不是空的)访问.done()回调中的ajax调用结果,对吗?如果是这样,我如何才能将结果返回到document.ready(),然后才能用该数据填充每个新列表?是的,但没有任何东西阻止您将数据保存到一个在“完成”回调之外可读的变量中。@XPD@Utkanos谢谢!!我将数据保存在一个全局变量中,然后在if语句
if(customerList)//do things
中检查其值。现在一切都很好。
$(document).ready(function () {
var ncustomers = 0;//number of customers
//Add first customer
ncustomers++;
AddCustomer(ncustomers);
//filling list with data fetched from api
fillCustomerList("#customer-1");
/*Trying to get list content*/
$("#customer-1 .customerList).html();//this is empty, since the request
//hasn't finished yet and filled the list
});