What's diffrence in jQuery ajax dataType="json" vs JSON.parse()

Viewed 29

Is there any real diffrence between using dataType='json' and parse response by JSON.parse(response) in jQuery Ajax?

$.ajax({
        url: path,
        type: 'POST',
        dataType: 'json',
        data: {
            block : lang,
        },
    }).done(function(response, textStatus, jqXHR)
    {
        output = response;
    });

VS

    $.ajax({
        url: path,
        type: 'POST',
        data: {
            block : lang,
        },
    }).done(function(response, textStatus, jqXHR)
    {
        output = JSON.parse(response);
    });
1 Answers

dataType: 'json':

  • Sets the Accept request header to tell the server that JSON is the desired response format
  • Attempts to parse the response as JSON regardless of what the server's Content-Type response header says the format is. (jQuery's default behaviour is to use the Content-Type to determine the correct parser).

JSON.parse:

  • Attempts to parse the response data as a string of JSON regardless of what it actually is (if the server responds with correctly labelled JSON, this will error since it will have already been parsed by jQuery).
Related