出于某种奇怪的原因,我的.getJSON()函数无法正常工作。它也没有给我任何错误消息。
我的JavaScript代码:
$(document).ready(function () {
console.log("Hello from riskanalysis.delete.js");
var categoryTd = $('#categoryId');
var categoryText = categoryTd.text();
var categoryInt = parseInt(categoryText);
console.log(categoryInt);
console.log(categoryText);
console.log("Hello before");
$.getJSON("/riskanalysis/getCategoryNameById?categoryId=" + categoryInt)
.done(function (categoryName) {
// On success
console.log("Category name is: " + categoryName);
categoryTd.text(categoryName);
}).fail(function (e) { console.log(e); });
console.log("Hello");
console.log("Hello after");
});
我的控制器代码:
[Route("riskanalysis/getCategoryNameById")]
[HttpGet]
public string GetCategoryNameById(int categoryId)
{
return _manager.GetCategoryNameById(categoryId);
}
我的管理员代码:
public string GetCategoryNameById(int categoryId)
{
using (var dbContext = new Entities.DanoneRiskanalysisContext())
{
Entities.Category entitiy = dbContext.Category
.Where(c => c.Id.Equals(categoryId))
.FirstOrDefault();
if (entitiy != null)
{
return entitiy.ListCategories;
}
}
return null;
}
我的管理员界面代码:
string GetCategoryNameById(int categoryId);
我的.cshtml代码:
<tr>
<td>Category</td>
<td id="categoryId">@Html.DisplayFor(model => model.categoryId)</td>
</tr>
添加了.fail函数,结果如下:
添加.fail(function( jqxhr, textStatus, error ) { var err = textStatus + ", " + error; console.log( "Request Failed: " + err ); });
结果:请求失败:parsererror,SyntaxError:位置0的JSON中的意外令牌T
有人知道为什么该功能不起作用吗?
已经感谢!
将$.getJSON()
更改为$.ajax
解决了我的问题!
[请修改您的控制器操作,以在客户端上使用.getJson时返回json响应。
[Route("riskanalysis/getCategoryNameById")]
[HttpGet]
public JsonResult GetCategoryNameById(int categoryId)
{
return Json(_manager.GetCategoryNameById(categoryId), JsonRequestBehavior.AllowGet);
}