简体   繁体   English

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

[英]Ajax request returns 200 OK, but an error event is fired instead of success

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage.我已经在我的网站上实现了一个 Ajax 请求,并且我正在从网页调用端点。 It always returns 200 OK , but jQuery executes the error event.它总是返回200 OK ,但jQuery执行错误事件。
I tried a lot of things, but I could not figure out the problem.我尝试了很多东西,但我无法弄清楚问题所在。 I am adding my code below:我在下面添加我的代码:

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 JqueryOpeartion.aspx 的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.成功删除后我需要("Record deleted")字符串。 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?解决此问题的正确方法是什么?

jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. jQuery.ajax尝试根据指定的dataType参数或服务器发送的Content-Type header 转换响应正文。 If the conversion fails (eg if the JSON/XML is invalid), the error callback is fired.如果转换失败(例如,如果 JSON/XML 无效),则会触发错误回调。


Your AJAX code contains:您的 AJAX 代码包含:

dataType: "json"

In this case jQuery:在这种情况下 jQuery:

Evaluates the response as JSON and returns a JavaScript object.将响应评估为 JSON 并返回 JavaScript object。 […] The JSON data is parsed in a strict manner; […] JSON 数据被严格解析; any malformed JSON is rejected and a parse error is thrown.拒绝任何格式错误的 JSON 并引发解析错误。 […] an empty response is also rejected; […] 空的回复也被拒绝; the server should return a response of null or {} instead.服务器应返回 null 或 {} 的响应。

Your server-side code returns HTML snippet with 200 OK status.您的服务器端代码返回 HTML 片段,状态为200 OK jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror . jQuery 期待有效的 JSON 并因此触发错误回调抱怨parseerror

The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:解决方案是从您的 jQuery 代码中删除dataType参数并使服务器端代码返回:

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"}

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

I've had some good luck with using multiple, space-separated dataType s ( jQuery 1.5+ ).我在使用多个以空格分隔的dataTypejQuery 1.5+ )方面运气不错。 As in:如:

$.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
});

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 policy in Chrome.在我的情况下,由于 Chrome 中的同源策略,我的 jQuery Ajax 请求无法成功。 All was resolved when I modified my server (Node.js) to do:当我修改我的服务器(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...我感觉自己很傻...

I reckon your aspx page doesn't return a JSON object.我认为您的 aspx 页面不会返回 JSON object。 Your page should do something like this (page_load)你的页面应该做这样的事情(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应该给你你得到的错误类型。

I have faced this issue with an updated jQuery library.我通过更新的 jQuery 库遇到了这个问题。 If the service method is not returning anything it means that the return type is void .如果服务方法没有返回任何内容,则意味着返回类型为void

Then in your Ajax call please mention dataType='text' .然后在您的 Ajax 通话中请提及dataType='text'

It will resolve the problem.它将解决问题。

You just have to remove dataType: 'json' from your header if your implemented Web service method is void.如果您实施的 Web 服务方法无效,您只需从 header 中删除dataType: 'json'

In this case, the Ajax call don't expect to have a JSON return datatype.在这种情况下,Ajax 调用预计不会有 JSON 返回数据类型。

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;

I had the same issue.我遇到过同样的问题。 My problem was my controller was returning a status code instead of JSON.我的问题是我的 controller 返回状态码而不是 JSON。 Make sure that your controller returns something like:确保您的 controller 返回如下内容:

public JsonResult ActionName(){
   // Your code
   return Json(new { });
}

I have the similar problem but when I tried to remove the datatype:'json' I still have the problem.我有类似的问题,但是当我尝试删除 datatype:'json' 时,我仍然遇到了问题。 My error is executing instead of the Success我的错误正在执行而不是成功

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

See this .看到这个 It's also a similar problem.这也是一个类似的问题。 Working I tried.工作我试过。

Dont remove dataType: 'JSON',不要删除dataType: 'JSON',

Note: Your response data should be in json format注意:您的响应数据应采用 json 格式

Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa.另一件事让我搞砸了,使用localhost而不是 127.0.0.1 ,反之亦然。 Apparently, JavaScript can't handle requests from one to the other.显然,JavaScript 无法处理从一个到另一个的请求。

If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed.如果您总是从服务器返回 JSON(没有空响应),则dataType: 'json'应该可以工作并且不需要contentType However make sure the JSON output...但是请确保 JSON output...

jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON! jQuery AJAX 将在有效但未序列化的 JSON 上引发“解析错误”!

I had the same problem.我有同样的问题。 It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.

Your script demands a return in JSON data type.您的脚本要求返回 JSON 数据类型。

Try this:尝试这个:

private string test() {
  JavaScriptSerializer js = new JavaScriptSerializer();
 return js.Serialize("hello world");
}

Try following尝试关注

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

OR或者

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

Use double quotes instead of single quotes in JSON object.在 JSON object 中使用双引号而不是单引号。 I think this will solve the issue.我认为这将解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对Struts2动作类的jQuery Ajax请求总是返回200 ok,但是会触发error事件 - jQuery Ajax request to Struts2 action class always returns 200 ok, but error event is fired Rails完成200 OK,但是$ .ajax()调用“错误”回调而不是“成功” - Rails completed 200 OK but $.ajax() calling 'error' callback instead of 'success' Ajax调用触发错误事件但返回200 ok - Ajax call fires error event but returns 200 ok Ajax请求仅返回错误,但状态码为200 OK - Ajax Request Only Returns Error But The Status Code Is 200 OK jquery ajax在直接执行时返回成功,但在附加到按钮时返回错误,即使服务器响应为200 OK - jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK jQuery $ .ajax使用JSONP调用跨域,返回状态200,但是错误函数被调用而不是成功 - jQuery $.ajax call for cross domain with JSONP, returns status 200, but error function is being called instead of success 带有原型的ajax请求以空白html页面返回200成功(间歇) - ajax request with prototype returns 200 success with blank html page (intermittent) Ajax 删除请求返回 200 但触发错误 - Ajax delete request returns 200 but fires error 即使响应为200,也可以访问ajax请求中的错误块 - access the error block in ajax request even the reponse is 200 ok jQuery AJAX 没有错误或成功触发 - jQuery AJAX no error or success fired
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM