空 XmlHttpRequest.response 但 XHR 包含我的数据
Empty XmlHttpRequest.response but XHR contains my data
我是 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 对象时我得到了这个:
所以我的问题是:
- 为什么
response
和 responseText
在 xhr 对象的第一行是空的?
- 如何检索我的数据?
给你,xmlhttprequest with json:
<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
希望对您有所帮助。
我是 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 对象时我得到了这个:
所以我的问题是:
- 为什么
response
和responseText
在 xhr 对象的第一行是空的? - 如何检索我的数据?
给你,xmlhttprequest with json:
<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
希望对您有所帮助。