0

I have some web application that uses jQuery to send AJAX requests to server. One of the methods (in controller) returns a ModelAndView object that can be a html code or JSON object - depends on errors existing. The input parameters of thid method is JSON array (form). The method definition:

@RequestMapping(value = "/generate", method = RequestMethod.POST, headers = BaseController.AJAX_HEADER)
public ModelAndView generate(@RequestBody HandlingReportForm form, HttpServletResponse response) {...}

The jQuery method looks like:

jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback,
    error : function(jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
    },
    complete : function(jqXHR, textStatus) {
        alert(textStatus);
    }
});

There is no problem when server returns a JSON array. The problem comes when server's response is html. I receive a "parseerror" exception. I suppose that jQuery trying to parse the response string to JSON. AM I right? How can I disable that automatic parsing? Is there another way to implement such universal method?

Thank you Thank you

1 Answer 1

1

The dataType has been mentioned as json, hence JQuery would try to interpret the response as an json object.

JQuery Ajax documentation -

dataType - "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

Its better to return a single response format.

You can also exclude the dataType argument.
If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I removed a dataType, so everything returns as string. Then I convert it to JSON if necessary. Thank you
By the way, it seems that latest versions of jQuery (I am using 1.6.2) can parse JSON object automatically even without specifing dataType attribute.
yup it interprets the datatype and should convert the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.