0


i made a servlet using java-ee (know as: j2ee)
the mvc is a controller (java), and views (html-js-css) pages

i hava a controller that mapping the url
like ...../controller/index.jsp

so if we navigate this, index.jsp will opened and all the js & css it need.

when user click on a button in the page, it will open an Ajax connection to the controller.
like i saw here:
calling a java servlet from javascript

$.get('../controller/url_to_mapped?firstStringParameter=aaa, function(responseData) {

});

for example: in the link i wrote below i send a string parameter called firstStringParameter and it's value is aaa.
how do i send a variable and not just a string parameters from js file??

if it's only in html code so we was write <% request.setAttribute("key", value)%>
but, in js i cant write java code.




edited:
Add some code:

servlet.java:

public class servlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.getRequestDispatcher("/test.jsp").forward(request,response);
    }
}



test.jsp:

<%@ page language="java" contentType="text/html; charset=windows-1255" pageEncoding="windows-1255"%>
<!DOCTYPE html>
<html>
<head>
        <script src="test.js"></script>
    </head>
    <body>
        <% String param = "foo";%>
    </body>
</html>



test.js

var param_js_context = '<%=param%>';
alert(param_js_context);

and the alert result was: <%=param%> as is.

Community
  • 1
  • 1
ofir_aghai
  • 3,017
  • 1
  • 37
  • 43

2 Answers2

2

As i got from your question following will be the solution

You have to create a variable in java script code only when you are writing you code in jsp file .

snippet are below

var foo = '<%=param%>';

and you can pass that parameter in ajax call as a javascript variable

Nilay Tiwari
  • 492
  • 5
  • 16
  • hi, i try exactly what the other guy write, i think this is what you meant, but its does not success. what controller get is only value `<%= id%>` as is. – ofir_aghai Oct 18 '14 at 17:25
0

use jQuery.ajax to post your variables like below:

String id = "123abc"; // your java string in jsp
   ...........

var id = "<%= id%>";   // java String is assigned to a javascript variable....

//Array ofyour javascript variables to be sent to the server:
var formData = {id:id, name:"ravi",age:"31"}; 
 
$.ajax({
    url : "AJAX_POST_URL",  //your servlet or jsp name/path
    type: "POST",
    data : formData,
    success: function(data, textStatus, jqXHR)
    {
        //data - response from server
      console.log("response..:"+ data);
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
       console.log("error...");
    }
});

try this and let us know. hope this will help your question.

Nomesh DeSilva
  • 1,649
  • 4
  • 25
  • 43