【问题标题】:localStorage.setItem for AJAX api call not defined until after function runs直到函数运行后才定义 AJAX api 调用的 localStorage.setItem
【发布时间】:2020-04-03 04:05:44
【问题描述】:

试图弄清楚为什么我的函数中的 localStorage.setItem 直到最后才运行。

jquery-3.3.1.min.js:2 OPTIONS http://169.254.10.10:8080/api/v0/sessions/undefined/operations/start 404(未找到)

console.log id 编号排在最后,在尝试了第二个 api 调用之后,根据我的错误,这将是有意义的。我知道帮助测试和验证很难,但如果有人能提供帮助,那就太好了。

0: {apiGatewayVersion: "1.24", activeTime: "0", id: 75 }
1: {apiGatewayVersion: "1.24", activeTime: "0", id: 76 }
2: {apiGatewayVersion: "1.24", activeTime: "0", id: 77 }
3: {apiGatewayVersion: "1.24", activeTime: "0", id: 78 }
length: 4


function startSession() {
    var _url = "http://169.254.10.10:8080/api/v0/sessions"
    $.ajax({
        "url": _url,
        "method": "GET",
        "timeout": 0,
        "headers": {
            "Content-Type": "application/json"
        },
    })
        .then(function (response) {
            var max = 0;
                for (var property in response) {
                max = (max < parseFloat(property)) ? parseFloat(property) : max;
                }
            var data = JSON.stringify(response[max]);
            var parse = JSON.parse(data);
            var id = parse.id;
            localStorage.setItem('id', id);
        console.log(localStorage.id);
});
    var _url2 = "http://169.254.10.10:8080/api/v0/sessions" + localStorage.id + "/operations/start"
    $.ajax({
        "url": _url2,
        "method": "POST",
        "timeout": 0,
        "headers": {
            "Content-Type": "application/json"
        },
});
    alert("Session Starting, Please wait...")
}

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您不能以localStorage.id直接访问本地存储项

    Read manual 并修复您的代码:

    var _url2 = "http://169.254.10.10:8080/api/v0/sessions/" + localStorage.getItem('id') + "/operations/start"
    
    

    由于您正在使用可能发生竞争条件的 Promise 行为,因此请确保您在成功获取会话后开始操作。

    我没有看到在操作开始期间使用本地存储的逻辑原因:

    function startSession() {
        var _url = "http://169.254.10.10:8080/api/v0/sessions"
        var request = $.ajax({
            "url": _url,
            "method": "GET",
            "timeout": 0,
            "headers": {
                "Content-Type": "application/json"
            },
        });
        request.then(function (response) {
          /*
          [
            {apiGatewayVersion: "1.24", activeTime: "0", id: 75 },
            {apiGatewayVersion: "1.24", activeTime: "0", id: 76 },
            {apiGatewayVersion: "1.24", activeTime: "0", id: 77 },
            {apiGatewayVersion: "1.24", activeTime: "0", id: 78 }
          ]
          */
          // Your session list is sorted by id order, 
          // and last session is last object in array
          // it's enough to get last object from response array
          var lastSession = (Array.isArray(response) && response.length)
                            ? response[response.length-1]
                            : {id: 0};
          localStorage.setItem('id', lastSession.id);
    
          var _url2 = "http://169.254.10.10:8080/api/v0/sessions/" + localStorage.getItem('id') + "/operations/start";
          // or simply:
          // var _url2 = "http://169.254.10.10:8080/api/v0/sessions/" + lastSession.id + "/operations/start";
          $.ajax({
            "url": _url2,
            "method": "POST",
            "timeout": 0,
            "headers": {
                "Content-Type": "application/json"
            },
          }).then(function(response) {
            console.log(response);
          });
    
          alert("Session Starting, Please wait...")
        });
    }
    
    

    附:如果响应是对象而不是数组:

    
          /*
          {
           0: {apiGatewayVersion: "1.24", activeTime: "0", id: 75 },
           1: {apiGatewayVersion: "1.24", activeTime: "0", id: 76 },
           2: {apiGatewayVersion: "1.24", activeTime: "0", id: 77 },
           3: {apiGatewayVersion: "1.24", activeTime: "0", id: 78 }
          }
          */
          response = Object.values(response); // add this
          var lastSession = (Array.isArray(response) && response.length)
                            ? response[response.length-1]
                            : {id: 0};
    

    【讨论】:

    • 感谢您的帮助,我使用 localStorage 是为了让会话 id 持续存在直到用户注销,然后删除操作被发送到 api 网关。看起来我可以选择使用会话存储。我们可能不会有太多同时用户,所以也许我不需要使用任何一个选项
    • @PA_Commons 在任何情况下我都给出了没有本地存储的替代答案(参见代码中的 cmets)。但是,是的,会话管理不应该在客户端进行。客户端唯一应该保留的是用于内部授权的会话 ID(访问令牌)。否则,您将赋予用户手动调用不同用户的会话操作开始的能力(也许不是)。
    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多