我试图传递一个JSON整数数组,但getJSON无法读取它(当我使用此处找到的虚拟JSON数组时,可以正常读取:https://jsonplaceholder.typicode.com/users)
尝试添加&callback=?
来处理CORS(跨源资源共享)问题,参考此处的建议(将getJSON更改为JSONP),因为我的API在另一个项目中。
遇到的问题:
- 回调函数与getJSON不起作用(即HTML表格已显示,但仍未填充。)
未能加载资源:服务器响应了404()状态
- 出现以下错误,但我不确定它们是否相关。
jquery.dataTables.min.css.:Uncaught SyntaxError: Unexpected token {
JSON数组API
// 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);
}
getJSON
<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>
$.getJSON
缺少一个闭合标签,但是你说没有错误,所以我必须假设这只是问题描述中的一个笔误。 - Tyler Roper