gpt4 book ai didi

javascript - 来自 REST API 的 HTTP 请求

转载 作者:行者123 更新时间:2023-12-01 02:46:04 24 4
gpt4 key购买 nike

我有这个API

[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}

我尝试使用此代码片段在我的 Javascript 上调用它;

function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}

但是,它只返回空的 XMLHttpRequest

我认为问题出在 URL 上。我如何能够调用我的 Javascript API?

最佳答案

由于您没有检查您的答案的响应,我怀疑您的后端有问题。但是,这里是一个功能解决方案的示例:

<!DOCTYPE html>
<html>
<body>

<h2>Using the XMLHttpRequest Object</h2>

<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>

<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>

</body>
</html>

您可以找到更多信息here 。但在行中

xhttp.open("GET", "api/myclass/data", true);

第二个参数是你的服务器中文件的地址。你确定你写的格式正确吗?您的data 文件的扩展名是什么。

我想,后端和前端都应该重新考虑。要做到这一点:

  1. 尝试使用 postman 向后端发送请求
  2. 在前端使用我的答案检查响应状态
  3. 确保将其设置为 async = false

    xhttp.open("GET", "api/myclass/data", false);

因此,不会出现 @Alex Kudryashev 指出的延迟

<小时/>

解决方案:

您需要首先找到该行的结果

console.log("Status is: "+this.status);

在浏览器的控制台中。

如果你得到的responseText为空,它可能是因为你从后端发送了一个空字符串,(我们不确定,因为你没有用 postman 测试你的后端)但是它了解响应状态至关重要。

关于javascript - 来自 REST API 的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47253411/

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