0

I'm working on a jsp page and I need a Javascript variable as parameter inside a java function e.g.:

<script>
    function example(string){
        <% javaFunction(string); %>
    }
</script>

how can I pass the javascript String variable to the java fucntion?

Y Zwen
  • 1

1 Answers1

2

DONT USE SCRIPTLETS IN JSP!.


You must understand jsp (views) code is executed in client side, java one is at server (host) one.

In order to get variables from the host side, you have plenty vays, but for small things best option is to make an ajax call:

$.get( "javaFunction", 
   { variable: "VALUE" } 
).done(function( data ) {
   alert("Java function returned " + msg);
});

In java you need to map the url:

@RequestMapping(value = "/javaFunction", method = RequestMethod.POST)
public
@ResponseBody
String javaMethod(@RequestParam("variable") String variable) {

    if (variable.equals("VALUE") {
        return "Correct call!";
    } else {
        return "Mistake!";
    }
}
Panda
  • 6,955
  • 6
  • 40
  • 55
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • Thank you for your reaction, when I try this method I get an error in my console. It says it cannot find the javaFunction in the directory where the jsp is in. I'm very new to Spring so I really appreciate the help here. errormessage:"POST http://localhost:8080/pages/javaFunction 404 (Not Found)" – Y Zwen Oct 27 '16 at 13:41
  • uhm... I think it was my mistake, I copied ajax call with url what is not correct in this case, kindly check my update and let me know how it works – Jordi Castilla Oct 27 '16 at 14:06
  • I still get the 404 error when I try this; "GET http://localhost:8080/pages/javaFunction?variable=VALUE 404 Not Found" – Y Zwen Oct 28 '16 at 06:53