簡體   English   中英

用於 AJAX api 調用的 localStorage.setItem 直到函數運行后才定義

[英]localStorage.setItem for AJAX api call not defined until after function runs

試圖弄清楚為什么我的函數中的 localStorage.setItem 直到最后才運行。

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

在嘗試第二個 api 調用之后,console.log id 編號排在最后,這根據我的錯誤是有意義的。 我知道很難幫助測試和驗證,但如果有人可以提供幫助,那就太好了。

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...")
}

您不能直接訪問本地存儲項作為localStorage.id

閱讀手冊並修復您的代碼:

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...")
    });
}

PS如果響應是對象而不是數組:


      /*
      {
       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};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM