我有以下一段 jquery 代码
var test = "test";
$.ajax({
url: root + "/servletPath",
type: "GET",
success: function (text) {
alert(text); // returns the right value
test = text;
},
error: function () {
}
});
// prints "test" and not the value that should be assigned in the success function
alert(test)
最佳答案
您在分配值之前提醒变量test
。 $.ajax
默认情况下是异步的。
可能的解决方案:
var test = "test";
$.ajax({
url: root + "/servletPath",
type: "GET",
success: function (text) {
test = text;
alertTest();
},
error: function () {
}
});
function alertTest(){
alert(test);
};
您还可以将 $.ajax
方法上的 async
属性设置为 false
,以同步运行代码。
关于javascript - 在 jquery 中从 ajax 请求分配一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23550322/