XMLHttpRequest responseText缺少字符

时间:2016-01-31 14:11:26

标签: javascript xmlhttprequest cgi

我似乎遇到了一个问题,我的onreadystatechange函数只用我的cgi脚本编写的部分字符串被调用。我猜测在cgi脚本写完输出之前正在调用onreadystatechange,我想知道是否有办法解决这个问题......我有以下内容

++

我正在进行以下调试:

      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {  
            debug("Got queryGraph response : " + xhttp.responseText);
            debug("parsing json...");
            var rtGd = JSON.parse(xhttp.responseText);
            // normal handler here...
          };
      xhttp.open("GET", "http://192.168.1.134/cgi-bin/web.cgi?queryGraph_"+timeStart+"_"+timeEnd, true);
      xhttp.send();

cgi脚本打印出数据,然后是Got queryGraph response : {"len":480, "msgIdx":4, "graphData":{ "Data1":[ {"t":1454247107,"v":20.19}, {"t":1454247109,"v":20.19}, {"t":1454247111,"v":20.19}, {"t":1454247113,"v":20.19}, {"t":1454247115,"v":20.19}, {"t":1454247117,"v":20.19}, {"t":1454247119,"v":20.19}, {"t":1454247121,"v":20.19} ], "Data2":[ {"t":1454247107,"v":19.94}, {"t":1454247109,"v":19.94}, {"t":1454247111,"v":19.94}, {"t":1454247113,"v":19.94}, {"t":1454247115,"v":19.94}, {"t":1454247117,"v":19.94}, {"t":1454247119,"v":19.94}, {"t":145424712 parsing json... (用于调试目的),但是数据的结尾和XXX没有出现......

XXX

1 个答案:

答案 0 :(得分:2)

在onreadystatechange回调中添加readystate项检查。 4的readystate意味着“完成” - https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState === 4) {
    debug("Got queryGraph response : " + xhttp.responseText);
    debug("parsing json...");
    var rtGd = JSON.parse(xhttp.responseText);
    // normal handler here...
  }
};
xhttp.open("GET", "http://192.168.1.134/cgi-bin/web.cgi?queryGraph_"+timeStart+"_"+timeEnd, true);
xhttp.send();