简体   繁体   中英

How to get data responseJSON when ajax request returns 4xx?

I have this Ajax request

    $.ajax({
        url: 'Default.aspx/CreateNewCase',
        data: JSON.stringify(
            {id: ID }
        ),
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (data, status) {
            //when server returns 200
            loadCase(ID, data);
        },
        error: function (data) {
            //when server returns 4xx. For example 409
            if(data.status == "409")
            {
                var newData = data.responseJSON;
                //error newData is undefined
                loadCase(ID, newData);
            }
        }
    });
    }

My WebMethod will always return an object whether the result is 200 or 4xx. On ajax.success, it returns a JSON object data. However on ajax.error, I cannot get the data.responseJSON.

I have read somewhere that JQuery prevents data to be read after an error. I have tried with .fail and .complete too, but I still cannot get the value when Ajax request returns 4xx.

How do I resolve this?

So I finally found the answer. I have to add this parameter inside <system.webServer> on the web.config:

  <system.webServer>
    <httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
      <clear/>
    </httpErrors>
  </system.webServer>

Then you can access your data like this:

error: function (data, status) {
       if (data.status == "409") {
             var myData = data.responseJSON;

             //do stuff here
       }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM