mercredi 18 mars 2015

Ajax call to Spring MVC controller redirects page instead of returning value

I'm a little bit confused. I'm writing an MVC application and have a simple controller like this:



@Controller
public class ProfileController {

final String DEFAULT_MALE_AVATAR = "../resources/graphics/avatarMan.PNG";
final String DEAULT_FEMALE_AVATAR = "../resources/graphics/avatarWoman.PNG";

@Autowired
UserService userService;

@RequestMapping(value = "/profile", method = RequestMethod.GET)
public String index() {

return "user/profile";
}

@RequestMapping(value = "profile/getavatar", method = RequestMethod.GET)
public @ResponseBody String getLoggedUserAvatar() {

String userMail = SecurityContextHolder.getContext()
.getAuthentication().getName();

User loggedUser;

if (userMail != null) {
loggedUser = userService.findUserByEmail(userMail);
return loggedUser.getAvatar();
} else {
return DEFAULT_MALE_AVATAR;
}
}


I've also got a simple js file called with "onload" in my body html tag while entering /profile section.



function init() {

var url = "profile/getavatar";

$.ajax({
url : url
}).then(function(data) {
avatarLink = data;
loadAvatar(avatarLink);
});

function loadAvatar(avatarLink){
$("#userAvatar").attr("src", avatarLink);
}

}


And for some strange reason I get ridirected to "profile/getavatar" and the page contains text with value returned by getLoggedUserAvatar(). The funny thing is I've also got some other controllers to other sections with almost the same js files and controllers - and they work like a charm.


What am I missing?


Aucun commentaire:

Enregistrer un commentaire