【发布时间】:2014-11-08 06:26:53
【问题描述】:
我在处理 ajax 结果的数组列表时遇到了奇怪的问题。
我在函数中传递了一个ID,并根据该Id获取结果-
@for (var i = 0; i < Model.Count; i++)
{
GetDates('@Model[i].contact_id');
}
功能-
var arrAcquiredDates = [];
function GetDates(contactid) {
$.ajax({
url: '/Service/ServicesRenewalDates/',
type: 'POST',
data: { Id: contactid },
success: function (data) {
console.log(data);
for (var i = 0; i < JSON.stringify(data.countof.Length) ; i++);
{
arrAcquiredDates.push('<tr><td colspan="4">' + data.list[i].DateAcquired + ' To ' + data.list[i].DateRenewal + '</td></tr>');
}
$('#tl-' + contactid).after(arrAcquiredDates);
}
});
}
因此,此函数从控制器调用方法并取回包含数组列表的结果-
public JsonResult ServicesRenewalDates(long? Id)
{
Bal b = new Bal();
List<ServiceModel> services = new List<ServiceModel>();
services = b.ServicesRenewalDates(Id);
return Json(new { list = services, countof = services.Count }, JsonRequestBehavior.AllowGet);
}
见表-
这是 UI 表格的一部分。如果您注意到第一行返回的数字是2,那么 ajax 会提供 2 次循环并获取我附加在列表中的相关结果。
但是从图像中你可以在这里看到它与想要的结果相反。其中Returned 编号为 2;它返回一行,对于1,它返回两行。
我在处理 ajax 时遇到了问题。
我的控制台结果是这样的-
现在终于到了我在表格中呈现列表的部分-
<table class="table table-responsive table-bordered table-striped">
<thead>
<tr>
<th>Customer Name</th>
<th>Returned Times</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr id="tl-@item.contact_id">
<td>@item.customerName
</td>
<td>@item.countCustomers</td>
</tr>
}
</tbody>
</table>
如何正确处理这个 ajax 结果?
【问题讨论】:
-
返回
countof似乎没有意义。您只需要return Json(list, JsonRequestBehavior.AllowGet);。如果值在 1 到 9 之间,data.countof.Length也将返回1,所以这没有任何意义(如果集合返回 8 个项目,它仍然只会循环一次)。而且您不断将新行附加到arrAcquiredDates,这就是您看到这些结果的原因。
标签: jquery arrays ajax asp.net-mvc