javascript - 空 XmlHttpRequest.response 但 XHR 包含我的数据

标签 javascript mongodb rest xmlhttprequest

我是 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 对象时我得到了这个:

Server response

所以我的问题是:

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

最佳答案

这里是带有 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

希望这有帮助。

关于javascript - 空 XmlHttpRequest.response 但 XHR 包含我的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31225999/

相关文章:

mongodb - mongoengine 连接和多个数据库

java - 基本身份验证请求应该是 POST 还是 GET?

c# - 判断是数组还是对象

java - 调用jsp中的非静态变量和静态函数

javascript - promise 中的 promise

javascript - 无法解析模块 'expo-font.js'

mongodb - 使用基于文档的 nosql(mongodb、couchdb 和 riak 等)查询关系数据的性能

javascript - 同时进行 2 个 Ajax 调用并在两个调用完成后回调?

javascript - 可接受空输入的 JS YouTube 正则表达式

javascript - Node.js - 使用回调插入 MongoDB