gpt4 book ai didi

json - 使用ajax获取json数据时出现500错误

转载 作者:行者123 更新时间:2023-12-04 23:53:24 24 4
gpt4 key购买 nike

我正在尝试使用 ajax 调用从我的 Controller 获取关于我的模型的 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);

数据 Controller

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

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

return Json(model);
}

最佳答案

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 方法应该返回一个 View ,通常 POST 方法会对发布的表单数据进行一些处理/ajax 数据并返回响应,可以是 JSON。但是如果你真的想从你的 GET 操作方法返回 Json 数据,你必须明确指定使用我们所做的上述方法

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

关于json - 使用ajax获取json数据时出现500错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33921025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com