【问题标题】:Empty XmlHttpRequest.response but XHR contains my data空 XmlHttpRequest.response 但 XHR 包含我的数据
【发布时间】:2015-07-05 08:12:16
【问题描述】:

我是 JS 新手,我正在使用 XHR 来连接托管在 mongolab 上的 mongodb。

我使用 REST 是因为 mongo 没有 js 驱动程序(他们只有 node.js 驱动程序,我不能将它用于我的项目)。 所以,我在我的数据库上使用了一个 GET 请求,然后我不知道如何检索响应。 这是我的 GET 函数:

function getRequest(callback){
  var xhr = getXMLHttpRequest();
  xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
           callback(xhr.responseText);
        }
    };

  xhr.open("GET",restURI+apiKey, true);
  xhr.send(null);
  console.log(xhr);
  console.log(xhr.responseText); 
}
function readData(sData) {
   XHR reading
    if (sData == "OK") {
        alert("All clear");
    } else {
        alert("Some issues");
    }
}

我尝试时得到一个空字符串:

console.log(xhr.response);

所以我曾经假设我的 REST 请求失败,但没有,在记录 xhr 对象时我得到了这个:

所以我的问题是:

  1. 为什么 xhr 对象的第一行 responseresponseText 为空?
  2. 如何检索我的数据?

【问题讨论】:

  • xmlhttp请求请参考这里:http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp。我建议您将您的 console.log 语句放在 onreadystatechange 方法中。您只有在(xmlhttp.readyState==4 && xmlhttp.status==200) 时才有数据。
  • 好吧,谢谢你的帮助,事实上我只需要把我的代码放在 readData 函数中就可以解决我的问题了。谢谢!

标签: javascript mongodb rest xmlhttprequest


【解决方案1】:

在这里,带有 json 的 xmlhttprequest:

<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
        myFunction(myArr);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; i < arr.length; i++) {
        out += '<a href="' + arr[i].url + '">' + 
        arr[i].display + '</a><br>';
    }
    document.getElementById("id01").innerHTML = out;
}
</script>

参考:http://www.w3schools.com/json/json_http.asp

希望对您有所帮助。

【讨论】:

  • 嗨!是的,非常感谢,我的日志放错了地方,你的代码让我更好地理解它应该如何工作:)
猜你喜欢
  • 1970-01-01
  • 2011-01-21
  • 1970-01-01
  • 2015-01-11
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多