【发布时间】:2020-08-15 03:47:42
【问题描述】:
由于某些奇怪的原因,我的 .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 ); });
结果:请求失败:解析器错误,语法错误:JSON 中位置 0 处的意外标记 T
有谁知道为什么这个功能不起作用?
已经谢谢了!
【问题讨论】:
-
除了 Hello 消息之外,您是否在控制台中看到任何错误?如果是,请发布这些错误。
-
除了“Hello 消息”之外,我在控制台中没有看到任何错误。
-
使用
fail即fail(function(e) { console.log(e); })完成后捕获错误 -
由于您只看到 Hello 消息,而不是成功函数中的 "Category Name" 消息,请编写一个 .fail 函数以了解确切的错误信息。我的猜测是,它可能无法解析 url - 例如,当 categoryInt 为 null 或 undefined 并且 MVC 将找不到任何采用 null 参数的端点 (riskanalysis/getCategoryNameById) 时。为了隔离问题,您可以硬编码 categoryInt 的一些值,看看它是否有效。或者可能是 categoryInt 被分配了 0。
-
我建议在您的控制器代码上设置一个断点,以查看 categoryId 是否甚至通过网络发送。
标签: javascript c# json asp.net-mvc getjson