首页 > 解决方案 > $.getJSON() 没有被触发

问题描述

出于某种奇怪的原因,我的 .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

有谁知道为什么这个功能不起作用?

已经谢谢了!

标签: javascriptc#jsonasp.net-mvcgetjson

解决方案


更改$.getJSON()$.ajax解决了我的问题!


推荐阅读