我正在尝试使用JQuery从SQL Server获取数据,我按照以下示例进行操作:link。但是,当我尝试检索数据时,却找不到错误。
1.我添加了EF,它使用表的列名生成了Context.cs文件。
2.创建API控制器:
public class GPSController : ApiController
{
public HttpResponseMessage Get()
{
List<gps> gpsList = new List<gps>();
using (DBModel dc = new DBModel())
{
gpsList = dc.gps.OrderBy(a => a.car_id).ToList();
HttpResponseMessage response;
response = Request.CreateResponse(HttpStatusCode.OK, gpsList);
return response;
}
}
}
带盖家用控制器:
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/scripts/jquery-3.3.1.min.js"></script>
<script src="~/scripts/bootstrap.min.js"></script>
<script src="~/scripts/GetData.js"></script>
<title>Index</title>
</head>
<body>
<div class="container py-4">
<h5 class="text-center">HOW TO RETRIEVE DATA FROM DATABASE IN THE ASP.NET Web API USING JQUERY</h5>
<div class="card">
<div class="card-header bg-primary text-uppercase text-white">
<h5 class="card-title">Employee List</h5>
</div>
<div class="card-body">
<button id="btnGetData" type="button" class="btn btn-outline-primary rounded-0">Load Employee List</button>
</div>
<div id="updatePanel" style="padding:20px;">
</div>
</div>
</div>
</body>
</html>
$(document).ready(function () {
var apiBaseUrl = "http://localhost:xxxxx/";
$('#btnGetData').click(function () {
$.ajax({
url: apiBaseUrl + 'api/gps',
type: 'GET',
dataType: 'json',
success: function (data) {
var $table = $('<table/>').addClass('dataTable table table-bordered table-striped');
var $header = $('<thead/>').html('<tr><th>gps_id</th><th>device_id</th><th>car_id</th><th>long</th><th>lat</th><th>speed</th><th>time_log</th></tr>');
$table.append($header);
$.each(data, function (i, val) {
var $row = $('<tr/>');
$row.append($('<td/>').html(val.gps_id));
$row.append($('<td/>').html(val.device_id));
$row.append($('<td/>').html(val.car_id));
$row.append($('<td/>').html(val.long));
$row.append($('<td/>').html(val.lat));
$row.append($('<td/>').html(val.speed));
$row.append($('<td/>').html(val.time_log));
$table.append($row);
});
$('#updatePanel').html($table);
},
error: function () {
alert('Error!');
}
});
});
});