USer22999299
USer22999299

Reputation: 5674

Spring MVC return simple text instead of JSON while using Ajax Call

This is my ajax call:

$.ajax({
        url: 'configuration/activePlatform/',
        type: 'GET',
        dataType: 'json',
        contentType: "application/json",
        success: function(data){
            console.log("getActivePlatform ACK");
            $('#activePlatform').append(data);
        },      
        error: function(xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message);
        }
    });

The response from this call is 200 OK.

I'm getting a clear text as the respone, the error msg is "Unexpected token s"

This is my server side code:

@Controller
@RequestMapping("/configuration")
public class configuration {

    @Autowired
    public CommonConfigurations configurations;


    @RequestMapping(value = "/activePlatform", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON)
    public @ResponseBody
    String activePlatform() throws Exception {

        return configurations.activePlatform;
    }
}

What did i do wrong?

Upvotes: 0

Views: 802

Answers (2)

Sagar
Sagar

Reputation: 838

You can return the entire configurations object from controller method and call data.activePlatform in your ajax callback assuming your configurations object is not too big to say you are carrying too much unnecessary data across the layers.

Upvotes: 0

Prakash Hari Sharma
Prakash Hari Sharma

Reputation: 1424

In your dispatcher-servlet.xml You will need to configure viewName “jsonTemplate” as bean of type MappingJackson2JsonView. And you will need to configure view resolver of type BeanNameViewResolver. This way viewName “jsonTemplate” will be matched with MappingJackson2JsonView and parsed JSON response will be returned to client.

 <mvc:annotation-driven/>  
 <bean name="viewResolver"  
class="org.springframework.web.servlet.view.BeanNameViewResolver"/>  
 <bean name="jsonTemplate"  
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>

Important :-

you need to have below jar in your classpath

  • jackson-annotations-2.6.0.jar
  • jackson-core-2.6.0.jar
  • jackson-databind-2.6.0.jar

I found this link useful.

Upvotes: 1

Related Questions