我需要一些帮助,我正在使用 jQuery 函数 $.ajax 从 MVC ASP.NET 应用程序使用 Web Api 服务,并且需要从数据库检索特定记录,我可以连接到该服务并检索根据提供的 id 提供正确的值,但我可以设法在表格中显示结果,我已经检查了属性名称,一切都很好,这是我的 javascript 代码
$("#boton_de_pabletoreto2").click(function () {
var id = $("#busqueda").val();
$.ajax({
type: "GET",
url: "http://localhost:55987/api/Empleado/"+ id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != null)
{
$.each(data, function (i, item) {
var rows = "<tr>" +
"<td id='id'>" + item.id + "</td>" +
"<td id='nombres'>" + item.Nombres + "</td>" +
"<td id='cargo'>" + item.Cargo + "</td>" +
"<td id='dpto'>" + item.Dpto + "</td>" +
"</tr>";
$('#Table').append(rows);
});
console.log(data);
}
else
{
alert("no se encontrarón datos");
}
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
}
});
});
这就是它所显示的
我知道它检索一条记录,因为从代码中得到了控制台中的应有记录
这是 HTML 代码
<div class="panel panel-primary">
<div class="panel-heading">
$.ajax pabletoreto
</div>
<div class="panel-body">
ID: <input type="text" id="busqueda"><br /><br />
<table class="table table-bordered" id="Table">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Departamento</th>
<th>Cargo</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-md-2 offset-md-2"><button id="boton_de_pabletoreto">Obtener Todos</button></div>
<div class="col-md-1"><button id="boton_de_pabletoreto2">Búsqueda</button></div>
</div>
<br />
我使用完全相同的代码(除了不需要提供 id 值和适当的 url:“http://localhost:55987/api/Empleados ”)来检索所有记录并且它有效
最佳答案
I know that it retrieves a record because from the code got the due record in console
因为您只获得一条记录作为 json 对象(而不是数组),所以 .each()迭代每个属性(这是你的问题......你的未定义元素):
var data = {id: 1, Nombres: 'Pablo Ern...', Cargo: 'Gerente', Dpto: 'Contabi...'};
$.each(data, function (i, item) {
console.log('Item(' + i + '): ' + item);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
在这种情况下,我建议避免循环并直接使用 json 对象:
var item = {id: 1, Nombres: 'Pablo Ern...', Cargo: 'Gerente', Dpto: 'Contabi...'};
var rows = "<tr>" +
"<td id='id'>" + item.id + "</td>" +
"<td id='nombres'>" + item.Nombres + "</td>" +
"<td id='cargo'>" + item.Cargo + "</td>" +
"<td id='dpto'>" + item.Dpto + "</td>" +
"</tr>";
$('#Table').append(rows);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-primary">
<div class="panel-heading">
$.ajax pabletoreto
</div>
<div class="panel-body">
ID: <input type="text" id="busqueda"><br/><br/>
<table class="table table-bordered" id="Table">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Departamento</th>
<th>Cargo</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-md-2 offset-md-2">
<button id="boton_de_pabletoreto">Obtener Todos</button>
</div>
<div class="col-md-1">
<button id="boton_de_pabletoreto2">Búsqueda</button>
</div>
</div>
<br/>
</div>
关于javascript - 通过 jQuery 检索并显示特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54117482/