我正在使用此代码在Asp.Net MVC中进行ajax调用
$.ajax({
type: "GET",
url: '@Url.Action("GetAllFacts", "Home")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//$('#AllFacts_Data').append("<div class='col-md-4'><div class='text-center facts-data-box bg_facts_grey'><div class='inner-div'><span><img src=" + data[0].ImageUrl + " class='image_top '></span><div class='text-center twit-all-content facts-content_blu'>'" + data[0].Content + "'</div></div></div></div>");
//$('#AllFacts_Data').append("<div class='col-md-4'><div class='text-center facts-data-box bg_facts_grey'><div class='inner-div'><span><img src=" + data[1].ImageUrl + " class='image_top '></span><div class='text-center twit-all-content facts-content_blu'>'" + data[1].Content + "'</div></div></div></div>");
},
error: function () {
alert("Error");
}
});
使用以下代码点击我的Get Method GetAllFacts()
[HttpGet]
public JsonResult GetAllFacts()
{
try
{
using (var context = new DbDemo())
{
var allData_Facts = context.Objblog.Take(2).ToList();
return Json(allData_Facts, JsonRequestBehavior.AllowGet);
}
}
catch (Exception)
{
}
return Json("false", JsonRequestBehavior.AllowGet);
}
这是我的代码,它正确地返回包含2个数据的列表,但在此之后它不会成功,它会根据Ajax错误函数发出错误警告。
我哪里错了?
答案 0 :(得分:0)
尝试
答案 1 :(得分:0)
AJAX:
$.ajax({
type: "GET",
url: '/Home/GetAllFacts',
dataType: "json",
success: function (data) {
if (data.success) {
// connect to server successful and everything's ok
// access to server returned data: data.alldata
} else {
// connect to server successful but something went wrong
alert(data.ex); // throw exception message
}
},
error: function () {
// connect to server failure
}
});
控制器:
[HttpGet]
public ActionResult GetAllFacts()
{
try
{
using (var context = new DbDemo())
{
var allData_Facts = context.Objblog.Take(2).ToList();
return Json(new { success = true, alldata = allData_Facts }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception e)
{
return Json(new { success = false, ex = e.Message }, JsonRequestBehavior.AllowGet);
}
}