繁体   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