【问题标题】:JSON array not being read by getJSONgetJSON 未读取 JSON 数组
【发布时间】:2019-10-16 18:20:47
【问题描述】:

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

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

遇到的问题:

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

加载资源失败:服务器响应状态为404()

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

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


【解决方案1】:

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

我将采用最明显的方式在您的操作方法之上装饰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>

【讨论】:

    【解决方案2】:

    尝试添加“最小宽度:700px;”到桌子上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多