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 "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/

相关文章:

javascript - 如何在屏幕中央显示模式弹出窗口并在调整屏幕大小时保持位置

javascript - 谁用 Jquery Ajax 附加 php onchange

javascript - 如何在时间进度条中放置时间显示框

php - 从 PHP 页面上的 jQuery AJAX 调用获取 JSON 数据

javascript - jQuery 获取点击链接的 css 值或告诉点击了哪个链接

javascript - 如何在 JavaScript 中组织继承以便能够将类放置在不同的文件中?

javascript - 无法根据下拉列表中选定的值过滤数据表数据

javascript - 获取 ajax $.post 数组响应

php - 网站。 AJAX 和 FIREFOX 问题。我认为 Firefox 不喜欢 ajax..?

javascript - 对变量的 JSON 调用的结果