JSON 数组未被 getJSON 读取

JSON array not being read by getJSON

我正在尝试传递一个 JSON 整数数组,但 getJSON 没有读取它。 (当我使用在这里 https://jsonplaceholder.typicode.com/users 找到的虚拟 JSON 数组时,它读起来很好)

尝试根据此处的建议添加 &callback=? 来处理 CORS (Changing getJSON to JSONP),因为我的 api 在另一个项目中。

遇到的问题:

  1. 回调不适用于 getJSON(即 HTML table 已显示但仍未填充。)

Failed to load resource: the server responded with a status of 404 ()

  1. 抛出了以下错误,但我不确定它们是否相关。

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);
    }

得到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>

Headers 对于 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>

您需要在您的服务器端添加 CORS header,有很多方法可以做到这一点,请参阅此 answer

我将采用最明显的方式在您的操作方法之上装饰 EnableCors 属性。

现在它将允许每个来源、header 和方法访问您的操作方法以进行测试,但在生产中将其更改为仅选定的来源、header 和方法。

现在,您可以继续 re-factor 您的代码,而不是进行字符串连接:

// GET api/dbretrieve
[HttpGet]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public JsonResult Get()
{
    HashSet<int> db = new HashSet<int>() { 2, 3, 5, 7, 11, 13 };

    // Project into your desired list
    var pidList = db.Select(x => new
    {
        pid = x
    });

    return Json(pidList, JsonRequestBehavior.AllowGet);
}

将您的 HTML 代码重构为:

<!DOCTYPE html>

<head>
  <title>JSON data to HTML</title>
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

  <!-- Popper JS -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>

  <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

  <!-- Latest D3.js -->
  <script src="https://d3js.org/d3.v5.min.js"></script>

  <!-- Latest jQuery Datatable CDN -->
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"></script>

  <script>
    $(document).ready(function() {

      function getData(callback) {
        const serverUrl = "http://localhost:44399/api/dbretrieve";
        $.ajax({
          url: serverUrl,
          type: 'GET',
          dataType: 'json',
          contentType: "application/json;charset=utf-8",
          success: function(data) {
            callback(data);
          },
          error: function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus);
          }
        });
      }

      function populateTable(data) {
        const table = $('#employee_table');
        table.find("tbody tr").remove();
        data.forEach(x => {
          table.append("<tr><td> </td><td>" + x.pid + "</td></tr>");
        });
      }

      // Get data from server now
      getData(populateTable);
    });
  </script>
</head>

<body>
  <div class="container">
    <div class="table table-hover 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>
</body>

尝试将 'min-width: 700px;' 添加到 table。