[英]Empty XmlHttpRequest.response but XHR contains my data
I'm new to JS and i'm using XHR in order to connect a mongodb hosted on mongolab. 我是JS的新手,我正在使用XHR来连接mongolab上托管的mongodb。
I use REST because mongo don't have a js driver (they got only node.js driver and I can't use it for my project). 我使用REST是因为mongo没有js驱动程序(它们只有node.js驱动程序,因此我无法在我的项目中使用它)。 So, I use a GET request on my DB, then I don't know how to retrieve the response.
因此,我在数据库上使用了GET请求,但是我不知道如何检索响应。 Here is my GET function :
这是我的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");
}
}
I got an empty string when I try : 我尝试时得到了一个空字符串:
console.log(xhr.response);
So I use to suppose that I failed in my REST request but no, when logging the xhr object i got this : 所以我经常假设我在REST请求中失败了,但是没有,在记录xhr对象时我得到了:
So my questions are : 所以我的问题是:
response
and responseText
are empty on the first line of the xhr object ? response
和responseText
为空? Here you are, xmlhttprequest with json: 您在这里,带有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>
Refer: http://www.w3schools.com/json/json_http.asp 请参阅: http : //www.w3schools.com/json/json_http.asp
Hope this help. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.