我有一个python文件,该文件将结果附加到日志文件中,我需要在UI中同步打印此日志。
以下是我的代码
var flag = 0;
function write_log_in_file(){
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/build5/builds/test.py",
"method": "POST",
"headers": {
"cache-control": "no-cache"
}
}
$.ajax(settings).done(function (response) {
flag =1;
console.log(response);
});
};
function get_log_from_file(){
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/build5/builds/build.log",
"method": "GET",
"headers": {
"cache-control": "no-cache"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
};
//Write build log in build.log file
write_log_in_file();
//Get log until python call is completed
while(!flag){
get_log_from_file();
}
在这里,我使用了标志变量,该变量已设置为1个AJAX呼叫完成后的1。在此之前,我的第二个Ajax调用被递归地称为。
由于我已经使用过,因此标志变量永远不会变为1,而在无限循环中进行。
还有其他方法,我可以递归地调用我的ajax函数,而其他AJAX函数已完成?
$.ajax
返回您可以链的承诺。
function write_log_in_file(){
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/build5/builds/test.py",
"method": "POST",
"headers": {
"cache-control": "no-cache"
}
}
return $.ajax(settings) // return a promise
};
function get_log_from_file(){
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/build5/builds/build.log",
"method": "GET",
"headers": {
"cache-control": "no-cache"
}
}
return $.ajax(settings) // return a promise
};
//Write build log in build.log file
write_log_in_file()
.then(function(result) {
console.log(result) // log write result
return get_log_from_file() // launch read
})
.then(function(result) {
console.log(result) // log read result
})
.catch(function(error) {
console.error(error);
});
yury的答案是使用诺言的好方法(您应该研究它)
但是您的代码问题是在JQuery的Ajax中没有记录的 .done 方法。您必须使用 .success 。
$.ajax(settings)
.success(function (response) {
flag = 1;
console.log(response);
})
.error(function(err) {
flag = -1; // End your while loop?
});