MikeW
MikeW

Reputation: 4809

How should I access a Spring MVC rest service using javascript?

I have a Spring-MVC based rest service returning json which is setup like so

@Controller
@RequestMapping("/api")
public class JSONController {

@Autowired
private FooService fooService;

@RequestMapping(value = "{name}", method = RequestMethod.GET)
public @ResponseBody
List<Foo> getFoos(@PathVariable String name) 

I plan on doing the rest of the CRUD operations through this api - what I was wondering was how should I write a client - using Json or JsonP?

At the moment I've retrieved the list of Foos with

    $.ajax({
    type: "GET",
    dataType: "jsonp",
    url: "http://xxx.com/rest/api/1",
    success: function(data){
        alert(data);
        $.each(data, function(index, data) {

            var foo = $.extend(new Foo(result[key].name));
            users.push(foo );

        });

    }
});

I can see the returned objects in firebug but the success callback is not reached. Is there a proper client side pattern for interacting with restful services?

Cheers!

Upvotes: 2

Views: 1927

Answers (1)

Eduardo Quintana
Eduardo Quintana

Reputation: 2388

It seems that your call is not reaching the success function because you are returning the list of you call in jsonp format. The mapper i think JacksonMapper is returning the list in "json" format.

If you use:

$.ajax({
    type: "GET",
    dataType: "json",
    url: "http://xxx.com/rest/api/1",
    success: function(data){
        alert(data);
        $.each(data, function(index, data) {

            var foo = $.extend(new Foo(result[key].name));
            users.push(foo );

        });

    }
});

It should work, I hope it helps.

Upvotes: 1

Related Questions