gpt4 book ai didi

jquery - 如何在ajax方法中为公共(public)变量设置值?

转载 作者:行者123 更新时间:2023-12-01 03:34:55 25 4
gpt4 key购买 nike

我尝试在ajax方法的外部使用ajax的结果并编写此代码,但出现错误:

TypeError: foods is null    

for (var j = 0; j <foods.obj.length; j++) {
<小时/>
$(document).ready(function () {
var foods = null;
$.ajax({
url: '/Train/TrianFood',
data: { Tarrif: 1 },
type: "POST",
context: this,
success: function (result) {foods = result;},
error: function () {}
});
var parentOfFood = $('#accordion1 .person-information');
for (var i = 0; i < parentOfFood.length; i++) {
var foodSelect = $(parentOfFood[i]).find('select[name$=Food]');

for (var j = 0; j <foods.obj.length; j++) {

foodSelect.append(new Option(foods.obj[j].ServiceType, foods.obj[j].ServiceTypeCode));
}
}
});

如何解决这个问题? enter image description here

最佳答案

这是因为loop在ajax响应回调之前执行。要解决此问题,请创建一个函数并在ajax响应后执行它。

尝试以下方式-

$(document).ready(function () {
var foods = null;
$.ajax({
url: '/Train/TrianFood',
data: { Tarrif: 1 },
type: "POST",
context: this,
success: function (result) {
foods = result;
foodSelectHandler();
},
error: function () {}
});
var parentOfFood = $('#accordion1 .person-information');

function foodSelectHandler(){
for (var i = 0; i < parentOfFood.length; i++) {
var foodSelect = $(parentOfFood[i]).find('select[name$=Food]');

for (var j = 0; j <foods.obj.length; j++) {

foodSelect.append(new Option(foods.obj[j].ServiceType, foods.obj[j].ServiceTypeCode));
}
}
}

});

关于jquery - 如何在ajax方法中为公共(public)变量设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37322252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com