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

jquery .aspx的c#代码

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

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


当前回答

我估计你的aspx页面不会返回JSON对象。 您的页面应该执行如下操作(page_load)

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

Response.Write(OutPut);

同时,试着改变你的AjaxFailed:

function AjaxFailed (XMLHttpRequest, textStatus) {

}

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

其他回答

另一件让我搞砸的事情是使用localhost而不是127.0.0.1,反之亦然。显然,JavaScript不能处理从一个到另一个的请求。

你只需要在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
});

我在使用多个空格分隔的数据类型(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
});

我估计你的aspx页面不会返回JSON对象。 您的页面应该执行如下操作(page_load)

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

Response.Write(OutPut);

同时,试着改变你的AjaxFailed:

function AjaxFailed (XMLHttpRequest, textStatus) {

}

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

我也有同样的问题。这是因为我的JSON响应包含一些特殊字符,并且服务器文件不是用UTF-8编码的,所以Ajax调用认为这不是一个有效的JSON响应。