在JS中存储变量的值

时间:2016-07-11 11:59:12

标签: javascript

由于我的主要语言是C,我习惯了指针,我喜欢它们。现在我有一些项目需要在Javascript中完成,而且我遇到了一个我不知道如何解决的问题。

我想存储从GET请求获得的变量的值。我有一个脚本将GET发送到PHP页面,然后将GET发送到我用C编写的守护进程。当我得到我想要的字符串时,我使用length来测量我得到的字符串的大小以及下一个GET请求我想发送我获得的字节数作为URL参数。

window.onload = function() {
  if (bytes === undefined) {
    var bytes = 0;
  }
  var url = "/test/log.php?q=" + bytes;

  function httpGet(url) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", url, true);
    xhttp.onload = function(e) {
      if (xhttp.readyState === 4) {
        if (xhttp.status === 200) {
          console.log(xhttp.responseText);
          var option = "";
          obj = JSON.parse(xhttp.responseText);
          for (var key in obj) {
            option += obj[key];
          }

          document.getElementById("list").innerHTML = asdf;
          bytes = option.length;
        }
      };
      xhttp.onerror = function(e) {
        console.error(xhttp.statusText);
      }
    };

    xhttp.send();
  }

  var updateInterval = 2000;

  function update() {
    httpGet(url);
    setTimeout(update, updateInterval);
  }

  update();
}

因此,重点是变量bytes。当脚本第一次被调用时,它应该具有值0,并且在每个循环之后(它每2秒循环一次,我没有在代码中显示循环)它应该具有前一个接收长度的值字符串。

3 个答案:

答案 0 :(得分:1)

您只需要确保将字节数param添加到您的网址中,其方式随每次调用而变化,而不是仅在页面加载时一次为0.

window.onload = function() {
  if (bytes === undefined) {
    var bytes = 0;
  }
  var url = "/test/log.php?q=";

  function httpGet(url) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", url, true);
    xhttp.onload = function(e) {
      if (xhttp.readyState === 4) {
        if (xhttp.status === 200) {
          console.log(xhttp.responseText);
          var option = "";
          obj = JSON.parse(xhttp.responseText);
          for (var key in obj) {
            option += obj[key];
          }

          document.getElementById("list").innerHTML = asdf;
          bytes = option.length;
        }
      };
      xhttp.onerror = function(e) {
        console.error(xhttp.statusText);
      }
    };

    xhttp.send();
  }

  var updateInterval = 2000;

  function update() {
    httpGet(url + bytes);
    setTimeout(update, updateInterval);
  }

  update();
}

答案 1 :(得分:0)

而不是url的固定值使其成为一个函数,如果你修改它,它将总是给你带有修改后的字节版本的当前Url

您只需更改此部分

var url = ...
// to 
function getUrl() {
  return "/test/log.php?q=" + bytes;
}

...
// and 
xhttp.open("GET", url, true);
// to
xhttp.open("GET", getUrl(), true);

答案 2 :(得分:-1)

我在一个上下文中声明变量,该函数在调用函数时不会清空它的值。所以,你可以声明你的变量" bytes"在函数之前,然后循环遍历该函数。在这种情况下,变量将保留最后一个值,直到您覆盖它为止。

这应该有用!

相关问题