Javascript 在jquery中从ajax请求分配值
我有以下jquery代码Javascript 在jquery中从ajax请求分配值,javascript,jquery,ajax,Javascript,Jquery,Ajax,我有以下jquery代码 var test = "test"; $.ajax({ url: root + "/servletPath", type: "GET", success: function (text) { alert(text); // returns the right value test = text; }, error: function () { } }); // prints "tes
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
,以同步运行代码 在赋值之前,您正在警告变量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
,以同步运行代码 在赋值之前,您正在警告变量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
,以同步运行代码 在赋值之前,您正在警告变量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
,以同步运行代码 AJAX是异步的。您应该像在异步运行AJAX时一样使用回调函数。AJAX是异步的。您应该像在异步运行AJAX时一样使用回调函数。AJAX是异步的。您应该像在异步运行AJAX时一样使用回调函数。AJAX是异步的。您应该像在异步运行AJAX时一样使用回调函数。