【发布时间】:2019-10-16 18:20:47
【问题描述】:
我正在尝试传递一个 JSON 整数数组,但 getJSON 没有读取它。 (当我使用https://jsonplaceholder.typicode.com/users 此处找到的虚拟 JSON 数组时,它读起来很好)
由于我的 api 在另一个项目中,因此尝试根据此处 (Changing getJSON to JSONP) 的建议添加 &callback=? 来处理 CORS。
遇到的问题:
- 回调不适用于 getJSON(即显示 HTML 表格但仍未填充。)
加载资源失败:服务器响应状态为404()
- 引发了以下错误,但我不确定它们是否相关。
jquery.dataTables.min.css.: Uncaught SyntaxError: Unexpected token {
JSON 数组接口
// GET api/dbretrieve
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
//TEST
HashSet<int> db = new HashSet<int>() { 2, 3, 5, 7, 11, 13 };
string json_string = "";
json_string = json_string + '[';
foreach (int s in db)
{
json_string = json_string + "{pid:" + s + "},";
}
if(Data.db.Count>0) json_string = json_string.Substring(0, json_string.Length - 1);
json_string = json_string + ']';
var json = JsonConvert.DeserializeObject(json_string);
return StatusCode(200, json);
}
获取JSON
<script>
$(document).ready(function () {
$.getJSON("https://localhost:44399/api/dbretrieve&callback=?", function (data) {
var employee_data = '';
$.each(data, function (key, value) {
employee_data += '<tr>';
employee_data += '<td>' + '</td>';
employee_data += '<td>' + value.pid + '</td>';
employee_data += '</tr>';
});
$('#employee_table tbody').append(employee_data);
});
});
</script>
正在传递的 JSON 数组
[{"pid":2},{"pid":3},{"pid":5},{"pid":7},{"pid":11},{"pid":13}]
HTML
<body>
<div class="container">
<div class="table-responsive">
<h1>Testing of database table</h1>
<br />
<table class="table table-bordered table-striped"
id="employee_table">
<thead>
<tr>
<th>#</th>
<th>pid</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
HTML 标头
<head runat="server">
<title>JSON data to HTML</title>
<script src="Scripts/jquery-3.0.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.9.0/d3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"></script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
【问题讨论】:
-
我只是复制+粘贴了您的 jQuery 和数组 with no issues。你能分享一下HTML吗? 编辑:您的
$.getJSON缺少结束标记,但您说没有错误,所以我不得不假设这只是问题中的一个错字。 -
@TylerRoper 嗨,是的,这是一个错字。感谢您的提醒:) 我已经编辑了我的帖子以及 HTML
-
你的数组 - 你
console.log(data)得到那个了吗?你确定这就是data在 JavaScript 中所代表的吗? -
@TylerRoper 是的,数据传递得很好,它(网址)与 Postman 一起使用。但是我在控制台日志中被抛出一个“请求的资源上没有'Access-Control-Allow-Origin'标头”错误
-
您的 API 调用存在一些问题。它可能无法为您提供所需的正确结果。
标签: jquery asp.net json cors getjson