Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  180] [ 2]  / answers: 1 / hits: 21317  / 10 Years ago, tue, october 28, 2014, 12:00:00

i'm trying to have a JavaScript file call a JavaSpring MVC Controller, then the controller will perform its request mapping functions.



I'm not sure if it is also possible to pass a variable to the controller so it can know which specific mapping to perform. IF one could demonstrate how to do both that would be immensely helpful. If one can simply show me how to call a controller via JS that would be very helpful as well and answer the question.



my controller will look similar to the following:



@Controller
@RequestMapping(value = /waterquality/scale)
public class NmWaidsController {
@RequestMapping(value = {,/})
public String homePageWaids(){
return waterquality/scale/calmix;
}


I would like the JS to call this controller.



If possible I would like to do the following, and have the JS pass a variable to the method which would look like the following:



@Controller
@RequestMapping(value = /waterquality/scale)
public class NmWaidsController {
@RequestMapping(value = {,/})
public String homePageWaids(int viewChoice){
switch(viewChoice){
case 1:
return waterquality/scale/calmix;
break;
case 2:
return waterquality/scale/caloddo;
break;
case 3:
return waterquality/scale/calstiff;
break;
default:
return error;
break;
}


Any help would be much appreciated! Thanks in advance!


More From » java

 Answers
29

Here's an example that you are looking for.



@RequestParam will help you out.



First, JSON object.



var loginData = { 
memberId : test1,
memberPw : test2
}


Second, Ajax.



 $.ajax({
type: POST,
url: YouActionName,
data: loginData,
success: function (result) {
// do something.
},
error: function (result) {
// do something.
}
});


And finally, your controller.
Remember the RequestParam's key names must be matched with the JSON's member key names. It's case sensitive, so be careful.



@RequestMapping(/YourActionName)
public String YourActionName(@RequestParam(memberId) String id, @RequestParam(memberPw) String pw ){
return new ModelAndView(ExpectedReturnView);
}





attaching event listner is really simple.



if you have html like this...



<div id=exampleDiv></div>


Then using basic id selector, you can attach an event like this below...



$('#exampleDiv').click(function(e) {
// do what you want when click this element.
});

[#68993] Friday, October 24, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luna

Total Points: 698
Total Questions: 114
Total Answers: 93

Location: Israel
Member since Wed, Apr 14, 2021
3 Years ago
luna questions
;