在从 ApiController 派生的 Controller 中的 Post 方法中,我应该返回什么来指示 jQuery 成功?
我试过 HttpResponseMessage 但 jQuery 将此视为错误(即使 jQuery 错误处理程序的参数显然具有 200 状态)。
jQuery 看起来像这样:
processParticipantEvent: function(parID, evtType, evtNotes, successFunction, errorFunction){
debugger;
var requestURL = '/api/participantevent';
var json = {"parId" : parID, "evtType": evtType, "evtNotes": evtNotes};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { successFunction(data); },
error: function (data) { errorFunction(data); }
});
},
我读过这个:Ajax request returns 200 OK, but an error event is fired instead of success这似乎涉及同一个问题,但我怀疑它没有数据,因为它对我不起作用?
要明确一点,我只想返回一个没有数据的普通旧 2xx。
最佳答案
根据 documentation :
"json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead.
因此,如果你想使用 jQuery ajax,你必须返回一个有效的 json 字符串,只需在你的 API Controller 中使用以下内容:
返回OK(new {});
请注意,这是一个 jQuery ajax“功能”,例如使用 Angular 来做一个 ajax post 我可以在我的 Controller 中使用 return Ok();
并且一切都按预期工作。
关于c# - .NET (ApiController)/jQuery .ajax : what to return from POST?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32554848/