gpt4 book ai didi

javascript - 从 REST API 读取 JSON 响应始终返回空文本

转载 作者:行者123 更新时间:2023-12-03 04:58:27 26 4
gpt4 key购买 nike

我希望一切顺利,如果您能帮助我或将我重定向到类似的旧帖子,我将不胜感激,因为我找不到。

我正在尝试发起 REST API 请求,服务器将发送 JSON 响应。该请求可以找到,但我无法读取 JSON 输出。状态始终返回 0。

这是我的代码。

<小时/>
<script>
function loadDoc() {

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "URL HERE", true);
xhttp.setRequestHeader("Content-type", "application/json")
xhttp.send();
var response = JSON.parse(xhttp.responseText);
document.getElementById("demo").innerHTML = response.Result;


}
</script>

我想打印这个 JSON 的结果:

{ 
Meta: {
Status: 'Success',
Debug: ''
},
Result: {
Count: 2584,
Error: [],
Info: [],
Skipped: [],
DuplicateResponseCount: 0,
DuplicateError: null
}
}

非常感谢。

最佳答案

正如巴勃罗所说。您正在使用异步。一种选择是使用 get 方法或仅将回调传递给函数。

function _post(url, callback) {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);

xhttp.onload = function() {
if (xhttp.status === 200) callback(xhttp.responseText);
else callback("error");
};
xhttp.send();

return xhttp.responseText;
}

_post("url here", function callback(response) {
// you can access response in here.
console.log(response);
});

在你的 PHP 脚本上

<?php
header("Access-Control-Allow-Origin: *");

关于javascript - 从 REST API 读取 JSON 响应始终返回空文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42339500/

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