【发布时间】: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 对象时我得到了这个:
所以我的问题是:
- 为什么 xhr 对象的第一行
response和responseText为空? - 如何检索我的数据?
【问题讨论】:
-
xmlhttp请求请参考这里:http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp。我建议您将您的 console.log 语句放在 onreadystatechange 方法中。您只有在
(xmlhttp.readyState==4 && xmlhttp.status==200)时才有数据。 -
好吧,谢谢你的帮助,事实上我只需要把我的代码放在 readData 函数中就可以解决我的问题了。谢谢!
标签: javascript mongodb rest xmlhttprequest