【发布时间】:2018-04-30 12:38:11
【问题描述】:
我正在做一个对服务器进行同步 ajax 调用的函数。 问题是当我调用函数时,main 不等待数据传播。
我更好地解释自己:
我需要从函数中返回一些数据:
var firstdate = getLastPaycheck();
这个函数是:
function getLastPaycheck() {
let returnValue = sessionStorage.getItem('last_paycheck');
if (returnValue == "" || returnValue == null) {
const message = { "cookie": getCookie("userCookie") };
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', complete, false);
xhr.open("POST", '/getLastPaycheck', false);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify(message));
function complete(e) {//Call a function when the state changes.
const response = JSON.parse(xhr.responseText);
console.log("Value taken from the server");
returnValue = moment(response.value[0].last_paycheck).format(getDateFormat("iso"));
return returnValue;
console.log("Returned value");
} // if readyStatus = 200;
} else {
console.log("Value taken from the session");
return returnValue;
}
}
问题是从服务器获取数据时,“firstdate”的值总是未定义。
有人可以解释一下怎么做吗?
谢谢。我很欣赏它。
【问题讨论】:
-
您的连接可能是同步的,但您仍然依赖于事件,而事实并非如此。此外,回调函数内部的 return 语句不会触发外部函数的返回。
标签: javascript ajax synchronization return