【问题标题】:500 Error when using ajax to get json data使用ajax获取json数据时出现500错误
【发布时间】:2015-11-25 15:59:35
【问题描述】:

我正在尝试使用 ajax 调用从我的控制器获取关于我的模型的 json 数据。我知道 500 错误可能意味着很多事情,但我想消除我犯简单错误的可能性。

控制台给我的错误是:500 Internal Service Error。 否则我可以在 url 中访问它就好了,但我在控制台中没有得到任何东西。

Index.cshtml

function getData() {
    $.ajax({
        url: "@Url.Action("dataTransfer", "Data")",
        type: "GET",
        dataType: "json",
        success: function(data) {
            console.log(data);
        },
        error: function() {
            console.log("failed");
        }
    });
}

setInterval(function() {
    getData();
}, 10000);

数据控制器

public JsonResult dataTransfer()
{
    string DataProvider = "Sample";

    var model = from d in db.Data
                where d.Name == DataProvider
                select d;

    return Json(model);
}

【问题讨论】:

    标签: json ajax asp.net-mvc


    【解决方案1】:

    500 internal error 表示您的服务器代码失败,由于代码错误而遇到异常!

    从您的代码中,我可以看到一个问题,这可能是您的错误的原因。

    从 GET 操作方法返回 Json 时,需要将 JsonRequestBehaviour.AllowGet 作为 Json 方法的第二个参数传递。

    public JsonResult dataTransfer()
    {
        string DataProvider = "Sample";
    
        var model = from d in db.Data
                    where d.Name == DataProvider
                    select d;
    
        return Json(model,JsonRequestBehavior.AllowGet);
    }
    

    通常在 ASP.NET MVC 应用程序中,GET 方法应该返回一个视图,并且通常 POST 方法对发布的表单数据进行一些处理/ ajax 数据并返回响应,可以是 JSON。但是如果你真的想从你的 GET 操作方法中返回 Json 数据,你必须明确指定使用我们所做的上述方法

    当然,Web API 有不同的概念(以及幕后的实现)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 2020-05-15
      • 2020-12-27
      • 2021-11-05
      • 2016-06-14
      相关资源
      最近更新 更多