javascript – 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);
}

JqueryOpeartion.aspx的C#代码

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

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

解决方法:

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

您的AJAX代码包含:

dataType: "json"

在这种情况下jQuery:

Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.

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

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

Content-Type: application/javascript

alert("Record Deleted");

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

Content-Type: application/json

{"message": "Record deleted"}

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...