ajax 请求后变量未更新
Variable is not updating after ajax request
我在 Vue 脚本中有下面的代码。
user_id = 100; //sample data
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "GET",
url: '/user',
success: function (user) {
user_id = user.user_id;
console.log(user_id); //returns 1
},
error: function (result) {
}
});
console.log(user_id); //returns 100 not 1
我希望能够存储 ajax 请求产生的值,即 1。但是,当我 console.log 在脚本末尾时,它 returns 100 不是 1。我认为我需要使用 promise/callback 来解决这个问题,但我不确定 how/what 我需要这样做。有人可以帮助我吗?
定义你的方法并return作为承诺。
function getUsers() {
return new Promise((resolve, reject) => {
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "GET",
url: '/user',
success: function (data) {
resolve(data);
},
error: function (error) {
reject(error);
}
});
});
}
您可以调用如下方法。
getUsers().then((data) => {
console.log(data); /* you will get the new data returned from ajax.*/
}).catch((error) => {
console.log(error);
});
一般情况下,您可以这样承诺回调:
let doXWithCallback = callback => {
// do x...
callback();
};
let doXPromisified = () => new Promise(doXWithCallback);
doXWithCallback(() => console.log('do x with callback'));
doXPromisified().then(() => console.log('do x promisified'));
具体针对您的示例:
let doRequest = () =>
new Promise((resolve, reject) =>
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "GET",
url: '/user',
success: user => resolve(user.user_id),
error: reject(),
}));
doRequest.then(userId => console.log('userId is', userId));
我在 Vue 脚本中有下面的代码。
user_id = 100; //sample data
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "GET",
url: '/user',
success: function (user) {
user_id = user.user_id;
console.log(user_id); //returns 1
},
error: function (result) {
}
});
console.log(user_id); //returns 100 not 1
我希望能够存储 ajax 请求产生的值,即 1。但是,当我 console.log 在脚本末尾时,它 returns 100 不是 1。我认为我需要使用 promise/callback 来解决这个问题,但我不确定 how/what 我需要这样做。有人可以帮助我吗?
定义你的方法并return作为承诺。
function getUsers() {
return new Promise((resolve, reject) => {
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "GET",
url: '/user',
success: function (data) {
resolve(data);
},
error: function (error) {
reject(error);
}
});
});
}
您可以调用如下方法。
getUsers().then((data) => {
console.log(data); /* you will get the new data returned from ajax.*/
}).catch((error) => {
console.log(error);
});
一般情况下,您可以这样承诺回调:
let doXWithCallback = callback => {
// do x...
callback();
};
let doXPromisified = () => new Promise(doXWithCallback);
doXWithCallback(() => console.log('do x with callback'));
doXPromisified().then(() => console.log('do x promisified'));
具体针对您的示例:
let doRequest = () =>
new Promise((resolve, reject) =>
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "GET",
url: '/user',
success: user => resolve(user.user_id),
error: reject(),
}));
doRequest.then(userId => console.log('userId is', userId));