Why is jqXHR.responseText returning a string instead of a JSON object?

后端 未结 5 533
鱼传尺愫
鱼传尺愫 2020-12-24 12:33

I have an $.ajax() request with the dataType set to \"json.\" The server is returning JSON with the correct mime type of \"application/json.\" And yet the responseText in my

5条回答
  •  渐次进展
    2020-12-24 13:24

    Step 1: Stringify the jqXHR

    var errorString = JSON.stringify(jqXHR.responseText);
    

    Step 2: change that string to Jquery Object

    var $errorObj = $(errorString);
    

    Step 3: Find and get what part of responseText you want.

    var errorMessage = $errorObj.find('p').eq(1).text(); 
    
    /* Here Im finding `Message:` thrown by the server, which is inside 

    tag */

    Thats it.

    $.ajax( /* ... */ ).fail( function(jqXHR, textStatus, errorThrown) {
    
         var errorString = JSON.stringify(jqXHR.responseText);
         var $errorObj = $(errorString);
         var errorMessage = $errorObj.find('p').eq(1).text();
    
         alert(errorMessage);
    
        } );
    

提交回复
热议问题