【问题标题】:How to set data from response to a var? [duplicate]如何设置从响应到var的数据? [复制]
【发布时间】:2021-03-18 12:40:39
【问题描述】:

我有(仍然错误resp = undefinited)。我测试请求返回数据正常。因为我对 JavaScript 有一点点的了解,所以我需要一小步来从请求的响应中设置数据。

    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "https://localhost:8443/control/jqxGeneralServicer?sname=JQGetListCustomerByCluster&deliveryClusterId=120120", true);
    xhttp.setRequestHeader('Content-Type', 'application/json');
    xhttp.send();

    var resp;
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
        resp = this.responseText        
        }
    }
    console.log("resp = " + resp);

我想resp里面有数据,怎么办?

【问题讨论】:

  • 在回调中访问它或等待它。当您调用console.log() 时,由于请求是异步的,它仍未设置。我还建议在分配onreadystatechange 事件后使用send
  • 我需要将数据移出xhtp.onreadystatechange 进行操作,这是我的主要目的。
  • 好像没有。我想将响应数据保存到变量或用于存储数据的东西。它可以使用外网xhttp.onreadystatechange,坚持下去。
  • 您可以很好地将响应值分配给回调中的外部范围变量。只是在加载值之前无法访问它,并且您需要一种方法来以某种方式对对该变量的访问进行计时。最简单的方法是从回调中调用一个函数,但是你不需要外部变量。异步编程提供了对程序流程的更改,您必须从一开始就设计异步程序架构,不可能使用同步结构。换句话说,你不能吃生的比萨。

标签: javascript


【解决方案1】:

我认为由于异步,您在控制台日志中看不到数据。 像这样修改一下,就会看到数据被赋值了。

var resp;
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        resp = this.responseText;
        console.log("resp = " + resp);
    }

}

【讨论】:

  • 我需要将数据移出xhtp.onreadystatechange 进行操作,这是我的主要目的。
  • 我知道,所以你需要回调或承诺之类的东西来处理 onreadystatechange 函数。
【解决方案2】:

您可以在此处访问您块内的evt

 xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
        resp = this.responseText        
        }
    }

你可以做到的:

let resp;
 xhttp.onreadystatechange = function(evt) {
        if (this.readyState == 4 && this.status == 200) {
          resp = evt.target.response;      
        }
    }

【讨论】:

猜你喜欢
  • 2017-12-20
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-26
相关资源
最近更新 更多