最近接到一个项目,说明如下:
创建一个 HTML 页面,该页面将调用我们的 API 端点以检索 API 记录器上的日志列表,将数据加载到视觉上令人愉悦的网格中。页面应每分钟进行一次此调用,并通过 AJAX 使用新数据更新现有行(部分页面更新,不应重新加载整个页面)。如果新数据中不再存在该行,则删除该行。如果任何行中都不存在新数据,请添加包含数据的新行。
API 调用将使用
POST
带有 jQuery AJAX 片段的方法对我们的 API 端点进行,具有以下 JSON 请求对象:{ "token": "CyvW1tW7hBMGNvSY752xr4QbK1TStbxhy8xSGfpMm1JxlSwjn7fXWU2LD7tVoP5przifFd0TnAHMJxf0maAvyAGN90FHfWk76IhO" }
来自服务器的 JSON Response 对象应如下所示:
{ "logs": [ { "Description": string, "ApplicationName": string, "Client_IP": string, "Server_IP": string, "RequestEndPoint": string, "LastOccurrence": datetime string, "ResponseCode": integer, "Last24HourLogCount": integer }, ] }
我在处理POST
请求和收集 JSON 数据时遇到问题。当我使用 Postman 进行 API 测试调用时,我能够接收 JSON 数据,但当我通过 HTML 页面进行调用时却无法接收,以下是我的尝试:
在这里,我POST
向端点创建了一个请求,并尝试将 JSON 数据转换为要在警报中显示的字符串:
我收到以下警报弹出窗口:
这是控制台中的消息:
如果我删除令牌标头并将 Postman 中的 JSON 数据添加到我的变量中,我会收到此控制台错误:
$.ajax({
type: "POST",
url: "https://fetch1.hipposhq.com/hipposapilogstatus",
data: data,
dataType: 'json',
headers:{
"token": "CyvW1tW7hBMGNvSY752xr4QbK1TStbxhy8xSGfpMm1JxlSwjn7fXWU2LD7tVoP5przifFd0TnAHMJxf0maAvyAGN90FHfWk76IhO"
},
success: function(data){alert(JSON.stringify(data))},
error: function(errMsg) {
alert(errMsg);
}
});
在这里,我创建了一个POST
对端点的请求并尝试在控制台日志中显示 JSON 数据,但我收到了一个错误:
这是控制台中的消息:
如果我删除令牌标头并将 Postman 中的 JSON 数据添加到我的变量中,我会收到相同的错误:
var data = {}
$.ajax({
type: "POST",
url: "https://fetch1.hipposhq.com/hipposapilogstatus",
data: data,
dataType: 'json',
headers:{
"token": "CyvW1tW7hBMGNvSY752xr4QbK1TStbxhy8xSGfpMm1JxlSwjn7fXWU2LD7tVoP5przifFd0TnAHMJxf0maAvyAGN90FHfWk76IhO"
},
success: function(data){
console.log(data);
}
});
在这里,我POST
使用从 Postman 收到的 JSON 数据(省略了实际数据)创建了一个请求,以接收 JSON 数据并将其显示在控制台日志中,但我收到了一个错误:
这是控制台中的错误:
当我添加令牌标头时,我收到相同的访问和资源错误:
$.ajax({
type:"POST",
url:"https://fetch1.hipposhq.com/hipposapilogstatus",
processData: false,
dataType: 'json',
data: JSON.stringify({
"logs": [
{
"Description": "string",
"ApplicationName": "string",
"Client_IP": "string",
"Server_IP": "string",
"RequestEndPoint": "string",
"LastOccurrence": "datetime string",
"ResponseCode": integer,
"Last24HourLogCount": integer,
},
]
}),
success: function(data){
console.log(data);
}
});
我希望能够在控制台中以字符串/对象/数组的形式接收 JSON 数据,以便将其显示在我的页面上,但我不确定从哪里开始。
您必须将令牌作为数据发送
const $output = $("#logs");
const process = response => $output.html(
response.logs.map(log => `<hr/><dl>${
Object.entries(log).map(([key,val]) => `<dt>${key}</dt><dd>${val}</dd>`).join("")
}</dl>`).join(""));
$.ajax({
type: "POST",
url: "https://fetch1.hipposhq.com/hipposapilogstatus",
dataType: 'json',
data: {
"token": "CyvW1tW7hBMGNvSY752xr4QbK1TStbxhy8xSGfpMm1JxlSwjn7fXWU2LD7tVoP5przifFd0TnAHMJxf0maAvyAGN90FHfWk76IhO"
},
success: process,
error: function(request, status, error) {
console.log(request.responseText);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="logs"><div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句