$.each(data, function (index, info) {
var a = info.notes;
var b = info.permission;
//var c = null;
var c = null;
$.ajax({
url: "assets/getExpiration.php?expiry=" + info.expiration,
type: "GET",
dataType: "text"
}, function(data){
c = data;
});
var z = null;
switch(info.stars) {
case 0: z = "<img src='assets/img/0star.png'/>"; break;
case 1: z = "<img src='assets/img/1star.png'/>"; break;
case 2: z = "<img src='assets/img/2star.png'/>"; break;
case 3: z = "<img src='assets/img/3star.png'/>"; break;
default: z = "<label class='label label-danger'>" + c + "</label>"; break;
}
var notes = a.length > 0 ? "<i class='fa fa-file'></i>" : "";
var permission = b.length > 0 ? "<i class='fa fa-warning'></i>" : "";
if (info.status == 'EXPIRED') {
$("#pendingCall" + info.callNum).append("<button onclick=\"loadPlayer('" + info.playerTag+ "', '" + info.status + "', "+ info.callNum +")\"class='btn btn-danger disabled'>" + info.username + " " + permission + " " + notes + "</button>");
} else {
$("#pendingCall" + info.callNum).append("<button onclick=\"loadPlayer('" + info.playerTag+ "', '" + info.status + "', "+ info.callNum +")\"class='btn btn-primary'>" + info.username + " " + permission + " " + notes + "<br> " + z + "</button>");
}
});
c未被编辑。但是当我在console.log(c)
内$.ajax()
时,它给了我正确的价值。但是,当我console.log()
之外的$.ajax()
时,它会给我'null'。我查了许多很多很多stackoverflow类似的问题,但所有的答案都没有用,或者我可能只是遗漏了一些东西。
答案 0 :(得分:0)
您是否假设代码来自:
var z = null;
switch(info.stars) {....
会等待你的ajax请求完成吗?如果是这样,那就不太合适了。
Ajax将异步激活请求,而其余代码继续执行(假设您没有指定它应该同步运行&lt; - 这不是一个好主意。)
如果你想使用AJAX返回的值,你需要将这个代码添加到ajax选项成功属性或类似的属性,它将在完成时执行。
答案 1 :(得分:0)
$ .ajax是一种即时返回的异步方法,但会在后台完成HTTP请求后运行成功和错误函数。
您需要将代码移动到$ .ajax方法中调用的自己的函数中。以下是一个例子。
$.ajax({
url: "assets/getExpiration.php?expiry=" + info.expiration,
type: "GET",
dataType: "text"
}, function (data) {
c = data;
var z = null;
switch(info.stars) {
case 0: z = "<img src='assets/img/0star.png'/>"; break;
case 1: z = "<img src='assets/img/1star.png'/>"; break;
case 2: z = "<img src='assets/img/2star.png'/>"; break;
case 3: z = "<img src='assets/img/3star.png'/>"; break;
default: z = "<label class='label label-danger'>" + c + "</label>"; break;
}
var notes = a.length > 0 ? "<i class='fa fa-file'></i>" : "";
var permission = b.length > 0 ? "<i class='fa fa-warning'></i>" : "";
if (info.status == 'EXPIRED') {
$("#pendingCall" + info.callNum).append("<button onclick=\"loadPlayer('" + info.playerTag+ "', '" + info.status + "', "+ info.callNum +")\"class='btn btn-danger disabled'>" + info.username + " " + permission + " " + notes + "</button>");
} else {
$("#pendingCall" + info.callNum).append("<button onclick=\"loadPlayer('" + info.playerTag+ "', '" + info.status + "', "+ info.callNum +")\"class='btn btn-primary'>" + info.username + " " + permission + " " + notes + "<br> " + z + "</button>");
}
});