Javascript Ajax 请求返回 200 OK,但会触发错误事件而不是成功
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6186770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ajax request returns 200 OK, but an error event is fired instead of success
提问by Pankaj Mishra
I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQueryexecutes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
我已经在我的网站上实现了一个 Ajax 请求,我正在从网页调用端点。它总是返回200 OK,但jQuery执行错误事件。
我尝试了很多东西,但我无法弄清楚问题所在。我在下面添加我的代码:
jQuery Code
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# code for JqueryOpeartion.aspx
C# 代码 JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted")
string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
("Record deleted")
成功删除后我需要该字符串。我可以删除内容,但没有收到此消息。这是正确的还是我做错了什么?解决这个问题的正确方法是什么?
回答by Salman A
jQuery.ajax
attempts to convert the response body depending on the specified dataType
parameter or the Content-Type
header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
jQuery.ajax
尝试根据指定的dataType
参数或Content-Type
服务器发送的标头转换响应正文。如果转换失败(例如,如果 JSON/XML 无效),则会触发错误回调。
Your AJAX code contains:
您的 AJAX 代码包含:
dataType: "json"
In this case jQuery:
在这种情况下,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.
将响应计算为 JSON 并返回一个 JavaScript 对象。[…] JSON 数据以严格的方式解析;任何格式错误的 JSON 都会被拒绝并引发解析错误。[...] 空响应也被拒绝;服务器应改为返回 null 或 {} 响应。
Your server-side code returns HTML snippet with 200 OK
status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror
.
您的服务器端代码返回带有200 OK
状态的HTML 片段。jQuery 期待有效的 JSON,因此会触发错误回调,抱怨parseerror
.
The solution is to remove the dataType
parameter from your jQuery code and make the server-side code return:
解决方案是dataType
从您的 jQuery 代码中删除参数并使服务器端代码返回:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
但我宁愿建议返回 JSON 响应并在成功回调中显示消息:
Content-Type: application/json
{"message": "Record deleted"}
回答by jaketrent
I've had some good luck with using multiple, space-separated dataType
s (jQuery 1.5+). As in:
我在使用多个以空格分隔的dataType
s ( 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
});
回答by Philippe Genois
You simply have to remove the dataType: "json"in your AJAX call
您只需删除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
});
回答by Corvin
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
这只是为了记录,因为我在寻找与 OP 类似的问题的解决方案时遇到了这篇文章。
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policyin Chrome. All was resolved when I modified my server (Node.js) to do:
就我而言,由于Chrome 中的同源策略,我的 jQuery Ajax 请求无法成功。当我修改我的服务器 (Node.js) 时,一切都解决了:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
我的头撞墙花了我一个小时的时间。我觉得自己很傻...
回答by LeftyX
I reckon your aspx page doesn't return a JSON object. Your page should do something like this (page_load)
我认为您的 aspx 页面不会返回 JSON 对象。你的页面应该做这样的事情 (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
另外,尝试更改您的 AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus
should give you the type of error you're getting.
textStatus
应该给你你得到的错误类型。
回答by Suresh Vadlakonda
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void
.
我在更新的 jQuery 库中遇到了这个问题。如果服务方法没有返回任何内容,则意味着返回类型是void
.
Then in your Ajax call please mention dataType='text'
.
然后在您的 Ajax 调用中请提及dataType='text'
.
It will resolve the problem.
它将解决问题。
回答by Bilel omrani
You just have to remove dataType: 'json'
from your header if your implemented Web service method is void.
dataType: 'json'
如果您实现的 Web 服务方法是无效的,您只需从您的标题中删除。
In this case, the Ajax call don't expect to have a JSON return datatype.
在这种情况下,Ajax 调用不期望有 JSON 返回数据类型。
回答by Terry Lin
Use the following code to ensure the response is in JSON format (PHP version)...
使用以下代码确保响应为 JSON 格式(PHP 版本)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
回答by Alexander Suleymanov
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
我遇到过同样的问题。我的问题是我的控制器返回的是状态代码而不是 JSON。确保您的控制器返回如下内容:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
回答by Rakesh Kumar
I have the similar problem but when I tried to remove the datatype:'json' I still have the problem. My error is executing instead of the Success
我有类似的问题,但是当我尝试删除 datatype:'json' 时,我仍然遇到问题。我的错误是执行而不是成功
function cmd(){
var data = JSON.stringify(display1());
$.ajax({
type: 'POST',
url: '/cmd',
contentType:'application/json; charset=utf-8',
//dataType:"json",
data: data,
success: function(res){
console.log('Success in running run_id ajax')
//$.ajax({
// type: "GET",
// url: "/runid",
// contentType:"application/json; charset=utf-8",
// dataType:"json",
// data: data,
// success:function display_runid(){}
// });
},
error: function(req, err){ console.log('my message: ' + err); }
});
}