我有问题从JSON响应中检索int值。这是我的代码:
$highestRow = $objWorksheet->getHighestRow();
public ActionResult GetCartCount()
{
int caounofcart = shoppingCartManager.GetCartItemsCount();
return Json(new { name = caounofcart });
}
我想通过JSON响应更改function updateQuantity() {
// code...
$("#cartbox").text(updatecart); // here is span element
// code...
}
function updatecart() {
$.getJSON("@Url.Action("GetCartCount", "Cart")", function(data) {
var items = [];
$each(data, function (key, val) {
items.push(val);
})
$("#cartbox").text(items[0]);
return items[0];
});
};
元素中的文本内容。我怎么能这样做?
答案 0 :(得分:0)
首先,使用您指定的逻辑无法实现此目的,因为AJAX请求是异步的。这意味着updatecart()
函数将在请求返回任何数据之前很久就会退出,因此不会向text()
提供任何值。
其次,您只在JSON响应中返回一个整数值,因此您只需使用data.name
来获取返回的计数。
考虑到这些问题,请尝试以下方法:
function updateQuantity(){
// code...
updateCart();
// code...
}
function updateCart() {
$.getJSON('@Url.Action("GetCartCount", "Cart")', function(data) {
$('#cartbox').text(data.name);
});
}