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

IT技术 javascript jquery asp.net ajax json
2021-01-26 18:37:30

我已经在我的网站上实现了一个 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);
}

C# 代码 JqueryOpeartion.aspx

protected void Page_Load(object sender, EventArgs e) {
    test();
}
private void test() {
    Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}

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

6个回答

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


您的 AJAX 代码包含:

dataType: "json"

在这种情况下,jQuery:

将响应计算为 JSON 并返回一个 JavaScript 对象。[…] JSON 数据以严格的方式解析;任何格式错误的 JSON 都会被拒绝并引发解析错误。[...] 空响应也被拒绝;服务器应改为返回 null 或 {} 响应。

您的服务器端代码返回带有200 OK状态的HTML 片段jQuery 期待有效的 JSON,因此会触发错误回调,抱怨parseerror.

解决方案是dataType从您的 jQuery 代码中删除参数并使服务器端代码返回:

Content-Type: application/javascript

alert("Record Deleted");

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

Content-Type: application/json

{"message": "Record deleted"}

您只需删除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
});

我在使用多个以空格分隔的dataTypes ( jQuery 1.5+ ) 方面取得了一些好运如:

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

这只是为了记录,因为我在寻找与 OP 类似的问题的解决方案时遇到了这篇文章。

就我而言,由于Chrome 中的同源策略我的 jQuery Ajax 请求无法成功当我修改我的服务器 (Node.js) 以执行以下操作时,一切都解决了:

response.writeHead(200,
          {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "http://localhost:8080"
        });

它真的花了我一个小时的时间用头撞墙。我觉得自己很傻...

我认为您的 aspx 页面不会返回 JSON 对象。你的页面应该做这样的事情 (page_load)

var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);

Response.Write(OutPut);

另外,尝试更改您的 AjaxFailed:

function AjaxFailed (XMLHttpRequest, textStatus) {

}

textStatus 应该给你你得到的错误类型。