<script>
function editComment(id) {
var content = $('#Content').val();
var modelData = { 'Id': id, 'Content': content };
$.ajax({
type: 'POST',
dataType: 'json',
url: '@Url.Action("EditC", "Comment")',
data: JSON.stringify({ model: modelData }),
contentType: 'application/json',
success: function () {
alert("YES");
},
error: function () {
alert("Error");
}
});
}
</script>
这里服务器返回200 OK,但由于某种原因正在调用错误函数。type
和contentType
似乎都是正确的。知道怎么解决这个问题吗?
编辑:后添加
error: function (xhr, textStatus, error) {
console.log(xhr.responseText);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
记录的内容:
parsererror
parsererror
SyntaxError: Unexpected end of JSON input
at parse (<anonymous>)
at ajaxConvert (jquery-3.4.1.js:9013:19)
at done (jquery-3.4.1.js:9483:15)
at XMLHttpRequest.<anonymous> (jquery-3.4.1.js:9785:9)
给以后的读者一个答案…
服务器确实返回一个成功的响应,但是一个空成功的响应:
return new HttpStatusCodeResult(200);
但是,客户端代码期望有效的JSON:
dataType: 'json',
因此,在收到成功的响应后,内部jQuery代码试图将该响应解析为JSON和,失败,导致触发error
回调。
由于没有响应体(在大多数情况下,即使有响应体,只要服务器返回正确的MIME类型),您不需要也不想在jQuery AJAX操作中指定dataType
。只需删除这部分:
dataType: 'json',