getJSON无法读取JSON数组

4

我试图传递一个JSON整数数组,但getJSON无法读取它(当我使用此处找到的虚拟JSON数组时,可以正常读取:https://jsonplaceholder.typicode.com/users

尝试添加&callback=?来处理CORS(跨源资源共享)问题,参考此处的建议(将getJSON更改为JSONP),因为我的API在另一个项目中。

遇到的问题:

  1. 回调函数与getJSON不起作用(即HTML表格已显示,但仍未填充。)

未能加载资源:服务器响应了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);
    }

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>

我刚刚复制粘贴了你的jQuery和数组没有问题。 你能分享一下HTML吗? 编辑:你的 $.getJSON 缺少一个闭合标签,但是你说没有错误,所以我必须假设这只是问题描述中的一个笔误。 - Tyler Roper
@TylerRoper 嗨,是的,那是一个笔误。谢谢你提醒我 :) 我已经修改了我的帖子以及HTML。 - user3803747
你的数组 - 你有打印“console.log(data)”来确认过吗?你确定这就是JavaScript中"data"所代表的吗? - Tyler Roper
@TylerRoper 是的,数据传递得非常好,而且它(URL)在Postman中也可以使用。然而,在控制台日志中,我遇到了“请求资源上缺少'Access-Control-Allow-Origin'头”错误。 - user3803747
您的 API 调用存在一些问题。它可能无法按照您期望的方式提供正确结果。 - Dilip Oganiya
显示剩余3条评论
2个回答

4

您需要在服务器端添加CORS头,有多种方法可以实现此目的,请参阅此答案

我将采用最明显的方法,在您的操作方法顶部装饰EnableCors属性。

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

现在,您可以继续重构您的代码,而不是使用字符串连接:

// 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>


-3
尝试在表格中添加'min-width: 700px;'。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接