我已经在我的网站上实现了一个 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>");
}
成功删除后我需要 ("Record deleted")
字符串。我可以删除内容,但没有收到此消息。这是正确的还是我做错了什么?解决这个问题的正确方法是什么?
最佳答案
jQuery.ajax
尝试根据指定的 dataType
参数或服务器发送的 Content-Type
header 转换响应正文。如果转换失败(例如,如果 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"}
关于javascript - Ajax 请求返回 200 OK,但触发了错误事件而不是成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6186770/