Ajax请求返回200 OK,但触发了错误事件,而不是成功。

21 浏览
0 Comments

Ajax请求返回200 OK,但触发了错误事件,而不是成功。

我在我的网站上实现了一个Ajax请求,并从一个网页调用该端点。它总是返回200 OK,但是jQuery执行了错误事件。

我尝试了很多事情,但是我无法找出问题。我在下面添加了我的代码:

jQuery 代码

var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});
function AjaxSucceeded(result) {
    alert("hello");
    alert(result.d);
}
function AjaxFailed(result) {
    alert("hello1");
    alert(result.status + ' ' + result.statusText);
}

JqueryOperation.aspx 的 C# 代码

protected void Page_Load(object sender, EventArgs e) {
    test();
}
private void test() {
    Response.Write("");
}

我需要在成功删除后获取(\"Record deleted\") 字符串。我可以删除内容,但是我没有得到这个消息。这是正确的吗,还是我做错了什么?解决这个问题的正确方法是什么?

admin 更改状态以发布 2023年5月22日
0
0 Comments

你只需要在你的AJAX调用中移除dataType: "json"

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'json', //**** REMOVE THIS LINE ****//
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

0
0 Comments

jQuery.ajax 试图根据指定的 dataType 参数或服务器返回的 Content-Type 标头转换响应体。如果转换失败(例如 JSON/XML 无效),则会触发错误回调。


你的 AJAX 代码包含:

dataType: "json"

在这种情况下,jQuery:

将响应评估为 JSON,并返回一个 JavaScript 对象。[...] JSON 数据以严格的方式解析;任何格式错误的 JSON 都将被拒绝,并抛出解析错误。[...] 还会拒绝空响应;服务器应该返回 null 或 {} 的响应。

你的服务器端代码返回了一个带有 200 OK 状态的 HTML 片段。jQuery 期望有效的 JSON,因此触发了错误回调并抱怨 parseerror

解决方法是从 jQuery 代码中删除 dataType 参数并让服务器端代码返回:

Content-Type: application/javascript
alert("Record Deleted");

但我更建议返回 JSON 响应并在成功回调中显示消息:

Content-Type: application/json
{"message": "Record deleted"}

0