使用Ajax获取JSON数据时出现500错误 [英] 500 Error when using ajax to get json data
问题描述
我正在尝试使用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);
DataController
public JsonResult dataTransfer()
{
string DataProvider = "Sample";
var model = from d in db.Data
where d.Name == DataProvider
select d;
return Json(model);
}
500内部错误意味着您的服务器代码失败,由于错误的代码而导致了异常!
从您的代码中,我可以看到一个可能是您的错误原因的问题.
从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具有不同的概念(以及幕后的实现)
I'm trying to use an ajax call to get json data about my model from my controller. I know 500 error could mean lots of things but I would like to eliminate the possibility of simple error by me.
Console gives me error of: 500 Internal Service Error
.
Otherwise I can access it in the url just fine but I don't get anything in the console.
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);
DataController
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 means your server code is failing, running into an exception because of bad code !
From your code, i can see a problem which could be the cause of your error.
When returning Json from a GET action method, you need to pass JsonRequestBehaviour.AllowGet
as the second parameter of Json
method.
public JsonResult dataTransfer()
{
string DataProvider = "Sample";
var model = from d in db.Data
where d.Name == DataProvider
select d;
return Json(model,JsonRequestBehavior.AllowGet);
}
Usually in an ASP.NET MVC application, the GET method's are supposed to be returning a view and typically the POST method does some processing on the posted form data/ajax data and return a response, which can be JSON. But if you really want to return Json data from your GET action method, You have to explicitly specify that using the above method we did
Ofcourse, Web API's has a different concept (And implementation behind the scene)
这篇关于使用Ajax获取JSON数据时出现500错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!