Javascript 从XMLHttpRequest检索响应负载元素

Javascript 从XMLHttpRequest检索响应负载元素,javascript,json,xmlhttprequest,elixir,elixir-poison,Javascript,Json,Xmlhttprequest,Elixir,Elixir Poison,我向应用程序登录发送JSON请求,但请求的类型对具有以下功能的服务器并不重要: function login() { var payload = { "api_key" : "", "cmd" : "login", "params" : {} } payload["params"]["username"] = document.getElementById("uname").value payload["params"]["password"] =

我向应用程序登录发送JSON请求,但请求的类型对具有以下功能的服务器并不重要:

function login() {
    var payload = {
    "api_key" : "", "cmd" : "login",
    "params" : {}
    }
    payload["params"]["username"] = document.getElementById("uname").value
    payload["params"]["password"] = document.getElementById("passwd").value

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://localhost:4000/api", true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.setRequestHeader("Accept", "application/json");

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            resp = JSON.parse(xhr.responseText);
            console.log("resp.status=" + resp.status);
            console.log("resp.[\"status\"]=" + resp["status"]);
        }
    }
    xhr.send(JSON.stringify(payload));
}
实际上,我在responseText字段中得到了正确的答复。例如,如果凭据错误,我会得到

{
  "status": "ko", 
  "errors": [
    {
      "cmd": "login",
      "long": "Login error : 'user-20' has no access to the system",
      "short": "login_error"
    }
  ]
}
如果证书是好的,我得到

{
  "status": "ok",
  ... some additional data
}   
但是,我无法获得status字段:resp.status或resp[status]始终未定义。如果调用在异步模式xhr.openPOST下完成,则相同,http://localhost:4000/api错误的或者如果我没有解析回复,比如:resp=xhr.responseText

更新-2017.09.06

我终于找到了让它工作的方法,但我不太明白为什么会这样。我真的变了

resp = JSON.parse(xhr.responseText);
进入

为了解决这个问题,我打印了xhr.responseText的类型,这是一个sting。实际上,typeofJSON.parsexhr.responseText也是一个字符串,这就是为什么它没有像status这样的字段。最后,两次解析xhr.responseText会得到一个我实际上可以从中检索数据的对象


如果有人对正在发生的事情有线索,我会感兴趣。。。我不知道这是否有关系,但发送JSON的应用服务器是Elixir/Phoenix的最新版本,即1.5/1.3,JSON编码/解码是用毒药完成的

这是因为您已将resp变量指定给responseText

resp=JSON.parsexhr.responseText

获取响应代码

respCode=xhr.status

或者,如果希望两者都位于同一resp变量中,则可以执行以下操作

resp = {
    responseText: xhr.responseText,
    status: xhr.status
}

然后您可以作为resp.responseText和resp.status访问它们

您可以添加JSON.stringifyxhr.responseText输出吗???@mszmurlo-您可以粘贴-console.logxhr.responseText;的输出吗@约翰巴布:对于失败的登录xhr.responseText={\status\:\ko\,\errors\:[{\short\:\login\u error\,\long\:\login error:user'user-20'无法访问系统\,\cmd\:\login\}\n。对于成功登录:xhr.responseText={\status\:\ok\,\data\:{\user\:{\username\:\user-20\,\user\u type\:\customer\,\user\u status\:\registed\,\sex\:null,\preferred\u language\:null,\msisdn\:\XXXXXXXXX\,\last\u name\:null,\first\u name\:null,\email\:\user-20@toto.com\},\api_key\:\84AFCFB03034A8898D590135D1B7174\}\n@mszmurlo-我觉得这个不错。只是一个粗略的猜测——我知道‘resp’不是一个局部变量——代码中是否有其他东西在改变‘resp’?你能在resp之前放一个“var”并在本地定义它并检查吗?我的问题不够清楚:我对xhr.status返回的HTTP respose代码不感兴趣,但对回复有效负载中返回的应用程序状态感兴趣。我应该在成功登录后获得ok,否则登录示例将失败。
resp = {
    responseText: xhr.responseText,
    status: xhr.status
}