簡體   English   中英

使用先前的ajax響應中的值更新發送到ajax調用的變量

[英]Update variable sent to ajax call with value from previous ajax response

我有一個ajax函數,每3秒執行一次,調用一個'file2.php'文件。 我通過POST傳遞了一個變量$ lastid,在'file2.php'中使用它,然后在響應中我得到了一個新的最后一個id,直到下一次執行ajax函數時,我需要以$ lastid的形式發送。 但是我找不到一種方法來更新實際上替換ajax調用中的先前值的變量。

我已經嘗試在ajax函數中將response.lastid分配給var lastid,但這無濟於事。 我一直都得到與上次通話相同的回復。

這是ajax函數,以及我最初如何設置變量

<script>
var lastid = <?php echo $lastid; ?>;

function nuevospedidos() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", "file2.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var response = JSON.parse(this.responseText);
      console.log(response);
      var lastid = response.lastid;
    }
  };
  xhttp.send("lastid=" + lastid);

}
setInterval(nuevospedidos, 3000);
</script>

我得到的響應是這個json對象

{lastid: "4074",
contenido: "some content",
originalid: "4073"}

我只想收到一次響應,然后用json對象帶來的lastid更新lastid變量,以便下次執行時知道是最后處理的id。

這是一個范圍問題。 在函數內部聲明時,您的lastid變量不是全局變量。

您必須將其聲明為全局變量:

var lastid = <?php echo $lastid ?>;
function newId() {
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "file2.php", true);
    xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var response = JSON.parse(this.responseText);
            lastid = response.lastid;
        }
    };
    xhttp.send("lastid=" + encodeURIComponent(lastid));
}
setInterval(newId, 3000);

您可以使用window對象來指定您正在訪問全局變量

window.lastid = response.lastid;

如此處所述: 如何將全局范圍變量引用到本地范圍?

暫無
暫無

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

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