.net核心web应用程序JQuery AJAX前端不从后端.net核心api获取数据

您所在的位置:网站首页 jquery做购物车 .net核心web应用程序JQuery AJAX前端不从后端.net核心api获取数据

.net核心web应用程序JQuery AJAX前端不从后端.net核心api获取数据

2023-04-11 18:02| 来源: 网络整理| 查看: 265

目前,我正在进行一项评估,这需要JQuery作为一种技术(我从未使用过)。我在努力把前端和后端连接起来。

我已经编写了一个.NET Core WebApi,它为学生和教师提供控制器(使用邮递员测试GET、POST、PUT、DELETE),我将添加更多内容,但我首先要测试连接。然后,我在相同的解决方案中创建了一个.Net核心WebApp。当我运行它们时,我可以访问邮递员的所有信息,但是注册日期的WebApp表值没有定义。表:

我的JSON响应,过去在‘Index’中的表:

如果这是个愚蠢的问题,我很抱歉。

从api提取的WebApp中的索引类:

@{ ViewData["Title"] = "Student"; } Get API Data ID Frist Name Last Name Date of Enrollment Active $(document).ready(function () { Manager.GetAllStudents(); }) var Manager = { GetAllStudents: function () { var obj = ""; var serviceUrl = "https://localhost:5001/api/student"; window.Manager.GetAPI(serviceUrl, onSuccess, onFailed); function onSuccess(jsonData) { obj = jsonData; $.each(jsonData, function (i, item) { var rows = "" + "" + item.StudentId + "" + "" + item.FirstName + "" + "" + item.LastName + "" + "" + item.DateOfEnrollment + "" + "" + item.Active + "" + ""; $('#Table').append(rows) }); } function onFailed(error) { window.alert(error.statusText); } return obj; }, GetAPI: function (serviceUrl, successCallback, errorCallback) { $.ajax({ type: "GET", url: serviceUrl, dataType: "json", success: successCallback, error: errorCallback }); }, }

启动:

using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews() .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); services.AddCors(options => { options.AddPolicy("_myAllowSpecificOrigins", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseCors(MyAllowSpecificOrigins); app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }

启动设置:

{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:3315", "sslPort": 44303 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "WebApp": { "commandName": "Project", "launchBrowser": true, "applicationUrl": "https://localhost:5001;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }

学生控制器

using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using System.Data.SqlClient; using System.Data; using WebAPI.Models; using System.Data.SqlTypes; namespace WebAPI.Controllers { [Route("api/[controller]")] [ApiController] public class StudentController : ControllerBase { private readonly IConfiguration _configuration; public StudentController(IConfiguration configuration) { _configuration = configuration; } [HttpGet] public JsonResult GetAllStudents() { string query = @" SELECT * FROM Students"; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("SchoolAppCon"); SqlDataReader myReader; using (SqlConnection myCon = new SqlConnection(sqlDataSource)) { myCon.Open(); using SqlCommand myCommand = new SqlCommand(query, myCon); myReader = myCommand.ExecuteReader(); table.Load(myReader); ; myReader.Close(); myCon.Close(); } return new JsonResult(table); } [HttpPost] public JsonResult Post(Student student) { string query = @" INSERT INTO Students(FirstName,LastName,DateOfEnrollment,Active) VALUES ('" + student.FirstName + @"' ,'" + student.LastName + @"' ,'" + student.DateOfEnrollment + @"' ,'" + student.Active + "')"; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("SchoolAppCon"); SqlDataReader myReader; using (SqlConnection myCon = new SqlConnection(sqlDataSource)) { myCon.Open(); using (SqlCommand myCommand = new SqlCommand(query, myCon)) { myReader = myCommand.ExecuteReader(); table.Load(myReader); ; myReader.Close(); myCon.Close(); } } return new JsonResult("Added Successfully"); } [HttpPut] public JsonResult Put(Student student) { string query = @" UPDATE Students SET FirstName = '" + student.FirstName + @"', LastName = '" + student.LastName + @"', DateofEnrollment = '" + student.DateOfEnrollment + @"', Active = '" + student.Active + @"' where StudentId = " + student.StudentId + @" "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("SchoolAppCon"); SqlDataReader myReader; using (SqlConnection myCon = new SqlConnection(sqlDataSource)) { myCon.Open(); using (SqlCommand myCommand = new SqlCommand(query, myCon)) { myReader = myCommand.ExecuteReader(); table.Load(myReader); ; myReader.Close(); myCon.Close(); } } return new JsonResult("Updated Successfully"); } [HttpDelete("{id}")] public JsonResult Delete(int id) { string query = @" DELETE FROM Students WHERE StudentId = " + id + @" "; DataTable table = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("SchoolAppCon"); SqlDataReader myReader; using (SqlConnection myCon = new SqlConnection(sqlDataSource)) { myCon.Open(); using (SqlCommand myCommand = new SqlCommand(query, myCon)) { myReader = myCommand.ExecuteReader(); table.Load(myReader); ; myReader.Close(); myCon.Close(); } } return new JsonResult("Deleted Successfully"); } } }

学生单元:

using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebAPI.Models { public class Student { public int StudentId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string DateOfEnrollment { get; set; } public string Active { get; set; } } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3