your programing

Ajax 요청이 200 OK를 반환하지만 성공 대신 오류 이벤트가 발생합니다.

lovepro 2020. 9. 29. 08:20
반응형

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

C # 코드 JqueryOpeartion.aspx

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서버에서 보낸 헤더 에 따라 응답 본문 변환을 시도 합니다. 변환이 실패하면 (예 : JSON / XML이 유효하지 않은 경우) 오류 콜백이 발생합니다.


AJAX 코드에는 다음이 포함됩니다.

dataType: "json"

이 경우에는 jQuery :

응답을 JSON으로 평가하고 JavaScript 객체를 반환합니다. […] JSON 데이터는 엄격한 방식으로 구문 분석됩니다. 형식이 잘못된 JSON은 거부되고 구문 분석 오류가 발생합니다. […] 빈 응답도 거부됩니다. 서버는 대신 null 또는 {} 응답을 반환해야합니다.

서버 측 코드는 200 OK상태 와 함께 HTML 스 니펫을 반환 합니다. jQuery는 유효한 JSON을 예상했기 때문에 parseerror.

해결책은 dataTypejQuery 코드에서 매개 변수 를 제거 하고 서버 측 코드를 반환하는 것입니다.

Content-Type: application/javascript

alert("Record Deleted");

그러나 오히려 JSON 응답을 반환하고 성공 콜백 내부에 메시지를 표시하는 것이 좋습니다.

Content-Type: application/json

{"message": "Record deleted"}

여러 개의 공백으로 구분 된 dataTypes ( 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
});

You simply have to remove the dataType: "json" in your AJAX call

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

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.

In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:

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. Your page should do something like this (page_load)

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

Response.Write(OutPut);

Also, try to change your AjaxFailed:

function AjaxFailed (XMLHttpRequest, textStatus) {

}

textStatus should give you the type of error you're getting.


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.

Then in your Ajax call please mention 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.

In this case, the Ajax call don't expect to have a JSON return datatype.


Use the following code to ensure the response is in JSON format (PHP version)...

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. Make sure that your controller returns something like:

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

Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.


See this. Its also similar problem. Working i tried.

Dont remove dataType: 'JSON',

Note: echo only JSON Formate in PHP file if you use only php echo your ajax code return 200


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.


If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...

jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!


Your script demands a return in JSON data type.

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. I think this will solve the issue.

참고URL : https://stackoverflow.com/questions/6186770/ajax-request-returns-200-ok-but-an-error-event-is-fired-instead-of-success

반응형