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

后端 未结 5 497
鱼传尺愫
鱼传尺愫 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:06

    I had the same problem. I returns a string because it formulated from an exception. E.g. I use a kernel listener with serialization to json on my Symfony2 project. Which is correct for proper REST headers.

    Anyway, just parse it; this works for me:

    $.ajaxSetup({
        "error": function(jqXHR, status, thrownError) {
            alert('error');
            var responseText = jQuery.parseJSON(jqXHR.responseText);
            console.log(responseText);
        }
    });
    
    0 讨论(0)
  • I don't see anything in the documentation that suggests responseText would be anything other than exactly what the name implies: text.

    Why not just use .getJSON? That would get rid of half of the code you wrote, and it'll convert the response to JSON. Win/win.

    0 讨论(0)
  • 2020-12-24 13:18

    Try

    $.ajaxSetup({
        "error": function(jqXHR, status, thrownError) {
            alert('error');            
            console.log(jqXHR.responseJSON);
        }
    });
    
    0 讨论(0)
  • 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 <p> 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);
    
        } );
    
    0 讨论(0)
  • 2020-12-24 13:29

    You are using $.ajax in a way the docs don't describe. Using json as the dataType just means that the data passed to the success callback will be parsed. Use it like this:

    $.ajax({
      dataType:'json',
      type: 'GET',
      url: "http://example.com/api/"
      success: function(data, textStatus, jqXHR) {
        // `data` contains parsed JSON
      },
      error: function(jqXHR, textStatus, errorThrown) {
         // Handle any errors
      }
    });
    
    0 讨论(0)
提交回复
热议问题