Controller:
public JsonResult Cars(int id)
{
JsonResult res = new JsonResult();
Cars entity = car.Cars.SingleOrDefault(a => a.CarNo == id);
res.Data = entity;
return Json(res, JsonRequestBehavior.AllowGet);
}
View:
<script type="text/javascript">
$("button").click(function () {
$.getJSON("/Compare/Cars?id=7", null,function (res) {
$("#name").html(res.CarNo);
});
});
</script>
<button>獲得 JSON 數據</button>
<div id= "name"></div>
不知道為什麼,獲取不到json,求大神解答一下
從給出的代碼看應該是按鈕單擊事件就沒綁定上,將按鈕單擊事件寫在$(function(){})裡面試下, $(function(){ $("button").click(function () {
$.getJSON("/Compare/Cars?id=7", null,function (res) {
$("#name").html(res.CarNo);
});
});
})