我无法找到一种方法来访问从我的控制器返回的以下json:
[{"ID":1,"seatnum":"A1","status":0},{"ID":2,"seatnum":"A2","status":0}]
我正在尝试访问每个seatnum值(A1,A2)以执行以下功能:
$.ajax({
url: 'seats/getseats',
dataType: "JSON",
error: function (data) {
$("table tr img").removeClass("available").attr("src", "images/taken.gif");
alert("error")
}
}).done(function (data) {
for (var i = 0; i < data.length; i++) {
//alert(data[i].seatnum);
var seatLetter = data[i][0];
var seatNumber = data[i].substr(1);
var $target = getImgFromSeat(seatLetter, seatNumber);
$target.removeClass("available").attr("src", "images/taken.gif");
}
如果它对我的Controller方法有帮助:
//
// GET: /seats/
public ActionResult Index()
{
return View(db.seats.ToString());
}
public JsonResult getseats()
{
var taken = from b in db.seats
select b;
taken = taken.Where(b => b.status.Equals(0));
return Json(taken, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:1)
我相信你正在寻找类似的东西:
$.ajax({
type: "GET",
url: '@Url.Action("getseats")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
for (var i = 0; i < data.length; i++) {
//alert(data[i].seatnum);
var seatLetter = data[i][0];
var seatNumber = data[i].substr(1);
var $target = getImgFromSeat(seatLetter, seatNumber);
$target.removeClass("available").attr("src", "images/taken.gif");
}
}
function errorFunc() {
alert('error');
}
返回的json是一个对象数组,所以不要像data [i] [0]那样访问它,你应该像data [i] .seatnum,data [i] .status等那样访问它。
此外,我建议您使用一些调试工具,例如浏览器开发人员工具,以便检查不同对象的值。
PS:不要对URL值进行硬编码。而是使用@ Url.Action(&#34; action-name&#34;)来生成它。