【问题标题】:How to Consume Apis from Asp .Net Core using Jquery如何使用 Jquery 从 Asp .Net Core 使用 API
【发布时间】:2020-03-25 23:42:44
【问题描述】:

我有这个 Asp Net Core Web Api 应用程序作为我的后端,其中包含使用默认路由系统 localhost\api\controller\id 所需的所有 API。从 PostMan 调用时,所有 API 都工作正常,但是当我尝试使用 Jquery Ajax 在我的前端调用它们时,事情无法正常运行。抱歉,如果这个问题看起来很愚蠢,我是 JavaScript 新手,非常感谢你们的帮助!

我只有 'Get' 方法可以在表格中列出修改 HTML 的结果:

$(document).ready(function () {
    $('#btn-lista-alunos').click(function () {
        $.ajax({
            url,
            type: 'GET',
            dataType: 'json', // Returns JSON
            success: function (response) {
                $('#tabela-alunos td').remove("");
                $('#info p').remove();
                var sTxt = '';
                $.each(response, function (index, val) {
                    sTxt += '<tr>';
                    sTxt += '<td>' + val.id + '</td>';
                    sTxt += '<td>' + val.nome + '</td>';
                    sTxt += '<td>' + val.ra + '</td>';
                    sTxt += '<td>' + val.curso + '</td>';
                    sTxt += '<td>' + val.periodo + '</td>';
                    sTxt += '<td>' + val.nota + '</td>';
                    sTxt += '<td>' + ValidaStatus(val.nota) + '</td>';

                    sTxt += '</tr>';
                });
                $('#tabela-alunos').append(sTxt);
            },
            error: function () {
                $('#info').html('<p>Ocorreu um erro, verifique a conexão com a api!</p>');
            }
        });
    });
    //Botao Limpar Lista
    $('#btnClear').click(function () {
        $('#tabela-alunos td').remove();
        $('#info p').remove();
    });
});

我的第一个 Html 页面:

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="Scripts/app.js"></script>
    <link rel="stylesheet" type = "text/css" href = "Content/content.css" />
    <title>Banco Alunos</title>
</head>

<body>
    <header>
        <h1>
            <p>Banco de Alunos</p>
        </h1>
    </header>

    <section class="sessao_botoes">
        <h2>
            <input onclick="location.href = 'incluir.html' ;" " id="btn-incluir" type="button" value="Incluir"/>
            <input id="btn-editar" type="button" value="Editar" />
            <input id="btn-excluir" type="button" value="Excluir" />
            <input id="btn-lista-alunos" type="button" value="Listar Alunos" />
            <input onclick="location.href = '' ;" " id="btn-incluir" type="button" value="Filtrar Alunos"/>
            <input id="btnClear" type="button" value="Limpar Listagem" />
        </h2>
    </section>

    <p><br /><br /></p>
    <section>
        <h3>
            <table id="tabela-alunos">
                <tr>
                    <th>ID</th>
                    <th>Nome</th>
                    <th>RA</th>
                    <th>Curso</th>
                    <th>Periodo</th>
                    <th>Nota</th>
                    <th>Status</th>
                </tr>
            </table>
            <div id="updatemessage"></div>
            <p id="info"></p>
        </h3>
    </section>

</body>

</html>

我的第二个带有帖子表单的 HTML 页面:

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="Scripts/app.js"></script>
    <title>Incluir Aluno</title>
</head>

<body>
    <header>
        <h1>
            <p>Incluir Novo Aluno</p>
        </h1>
    </header>
    <section>
        <h2>
            <form id="myForm" action="http://localhost:51700/api/Alunos" method="post">
                <p>
                    <label>Nome: </label>
                    <input type="text" name="nome">
                </p>
                <p>
                    <label>RA: </label>
                    <input type="number" maxlength="8" name="ra">
                </p>
                <p>
                    <label>Periodo: </label>
                    <input type="text" name="periodo">
                </p>
                <p>
                    <label>Curso: </label>
                    <input type="text" name="curso">
                </p>
                <p>
                    <label>Nota: </label>
                    <input type="number" max="10" maxlength="4" name="nota">
                </p>
                <p>
                    <input id="btnCadastro" type="submit" value="Cadastrar">
                </p>
            </form>
            <p>
                <input onclick="location.href = 'index.html'" type="submit" value="Voltar">
            </p>
        </h2>
    </section>
</body>

</html>

如何使用 Ajax 将表单作为 JSON 发送到我的后端并编辑/删除第一页上列出的对象值?我已经尝试了很多东西,但都没有奏效。谢谢!

【问题讨论】:

    标签: javascript jquery html .net asp.net-core


    【解决方案1】:

    所以我在这里... 我学会了如何用 ajax 调用它们中的大多数: PS:在我的 web asp net core BackEnd 中,我必须做很多与 CORS 相关的东西才能调用 API,请点击链接了解更多详细信息:https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-javascript?view=aspnetcore-3.0

    //Get
    $.ajax({
       url: "url",
       type: 'GET',
       dataType: 'json',
       success: function (response) {
       //do something}
    });
    
    
    //Post
    $.ajax({
       headers: {
       Accept': 'application/json',
                 'Content-Type': 'application/json'
    },
       type: 'POST',
       url: "url",
       data: JSON.stringify(cadastro),
       uccess: function (result) {
       $("#myForm")[0].reset();
       alert("Sucesso");
    },
       error: function () {
       alert("error");
    }
    });
    
    
    //DeleteOne
        $.ajax({
            url: "url/" + id,
            type: 'DELETE',
            success: function (result) {
                $(param).parents("tr").remove();
            }
    });
    

    【讨论】:

      【解决方案2】:

      第一件事是为什么你使用 HTML 页面而不是 asp.net core cshtml 页面?提供页面的框架有很多特性,比如模型绑定。

      您可以使用 jquery 从您的 html 页面中获取值,然后使用 Ajax 将数据发布到服务器端:

      var data = { 
          StartDate: "1/19/2016",
          EndDate: "4/19/2016",
          ProductType: "New",
          Count: 1
      };
      
      $.ajax({
      url: '/Home/Edit',
      type: 'POST',
      data: JSON.stringify(data),
      contentType: 'application/json; charset=utf-8',
          success: function (data) {
              window.location.href = "";
      }
      });
      

      在ajax的成功函数中,可以使用window.location.href重定向到另一个页面,如上图。

      在服务器端,您可以使用FromBody 从请求正文中获取值:

      public IActionResult Edit([FromBody]MyViewModel myViewModel)
      {
          if (ModelState.IsValid)
          {
      
          }
          return Json("OK");
      }
      
      public class MyViewModel {
      
          public DateTime StartDate { get; set; }
          public DateTime EndDate { get; set; }
          public string ProductType { get; set; }
          public int Count { get; set; }
      }
      

      【讨论】:

      • 是故意的,我被教唆如何让不同场景下的系统在它们之间进行数据通信。现在一切都好。谢谢!
      猜你喜欢
      • 2016-10-21
      • 2021-06-25
      • 1970-01-01
      • 2019-03-10
      • 2021-11-14
      • 2022-07-13
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      相关资源
      最近更新 更多