如何访问从 Ajax 返回的数据 post 方法调用与索引,就像数组一样



这是我的代码,它对成功功能不起作用。是否有可能我没有以正确的方式指定tr和td元素

$(document).ready(function () {
$("#search").blur(function () {
//alert("ilir");
$.ajax({
type: "POST",
data: { "barkodi": $(this).val() },
dataType: 'json',
success: function (data) {
$('tr[class!="info"]').remove().after(function () {
$.each(function (index, data) {
$("tr").append(
$("<tr></tr>").html(
$("<td></td>").text(data[0].Barkodi),
$("<td></td>").text(data[0].Emri),
$("<td></td>").text(data[0].Cmimi),
$("<td></td>").text(data[0].Sasia))
);
});
});
}
});
});
})

这是我的控制器和操作方法,我不知道我的错误在哪里:(

[HttpPost]
[AllowAnonymous]
public JsonResult Index(string barkodi)
{
var produkti = _context.Produktets.SingleOrDefault(x => x.Barkodi == barkodi);
List<ProduktetCustom> prod = new List<ProduktetCustom>();
ProduktetCustom produkt = new ProduktetCustom()
{
Barkodi = produkti.Barkodi,
Emri = produkti.Emri,
Sasia = produkti.Sasia,
Cmimi = produkti.Cmimi,
Pershkrimi = produkti.Pershkrimi,
IsDeleted = produkti.IsDeleted,
DataModifikimit = produkti.DataModifikimit,
DataShtimit = produkti.DataShtimit
};
prod.Add(produkt);
return Json(prod,JsonRequestBehavior.AllowGet);
}

您应该使用Array中定义的forEach函数而不是$.each

您的代码将如下所示:

success: function (data) {
$('tr[class!="info"]').remove().after(function () {
data.forEach(function (item, index) {
$("tr").append(
$("<tr></tr>").html(
$("<td></td>").text(item.Barkodi),
$("<td></td>").text(item.Emri),
$("<td></td>").text(item.Cmimi),
$("<td></td>").text(item.Sasia)
)
);
});
});
}

你是对的;问题是你如何在html()方法中添加元素。它只接受字符串或函数。您还将遍历data数组,但仅重复添加第一项中的内容。您还尝试将内容放置在已删除的元素after(),这将不起作用。

试试这个:

success: function (data) {
var html = data.map(function(o) {
return `<tr><td>${o.Barkodi}</td><td>${o.Emri}</td><td>${o.Cmimi}</td><td>${o.Sasia}</td></tr>`;
}).join('');
$('table tbody').append(html);
}

var data = [{
Barkodi: 'Barkodi 1',
Emri: 'Emri 1',
Cmimi: 'Cmimi 1',
Sasia: 'Cmimi 1',
}, {
Barkodi: 'Barkodi 2',
Emri: 'Emri 2',
Cmimi: 'Cmimi 2',
Sasia: 'Cmimi 2',
}]
var html = data.map(function(o) {
return `<tr><td>${o.Barkodi}</td><td>${o.Emri}</td><td>${o.Cmimi}</td><td>${o.Sasia}</td></tr>`;
}).join('');
console.log(html);
$('table tbody').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table><tbody></tbody></table>

未测试,但您可以尝试parseJSON.

var objArray = $.parseJSON(data);
$.each(function (index, objArray) {
//other stuff
});

最新更新