gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:39:39 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com