Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  33] [ 4]  / answers: 1 / hits: 30595  / 15 Years ago, mon, january 25, 2010, 12:00:00

I have session key that is a JavaScript variable which I got from a REST API call. I need to call my Java code in a servlet and pass that key as a parameter. What JavaScript function can I use to do that?


More From » jsp

 Answers
8

Several ways:




  1. Use window.location to fire a GET request. Caveat is that its synchronous (so the client will see the current page being changed).



    window.location = http://example.com/servlet?key= + encodeURIComponent(key);


    Note the importance of built-in encodeURIComponent() function to encode the request parameters before passing it.


  2. Use form.submit() to fire a GET or POST request. The caveat is also that its synchronous.



    document.formname.key.value = key;
    document.formname.submit();


    With



    <form name=formname action=servlet method=post>
    <input type=hidden name=key>
    </form>


    Alternatively you can also only set the hidden field of an existing form and just wait until the user submits it.


  3. Use XMLHttpRequest#send() to fire an asynchronous request in the background (also known as Ajax). Below example will invoke servlets doGet().



    var xhr = new XMLHttpRequest();
    xhr.open(GET, http://example.com/servlet?key= + encodeURIComponent(key));
    xhr.send(null);


    Below example will invoke servlets doPost().



    var xhr = new XMLHttpRequest();
    xhr.open(POST, http://example.com/servlet);
    xhr.setRequestHeader(Content-Type, application/x-www-form-urlencoded);
    xhr.send(key= + encodeURIComponent(key));

  4. Use jQuery to send a crossbrowser compatible Ajax request (above xhr code works in real browsers only, for MSIE compatibility, youll need to add some clutter ;) ).



    $.get(http://example.com/servlet, { key: key });




    $.post(http://example.com/servlet, { key: key });


    Note that jQuery already transparently encodes the request parameters all by itself, so you dont need encodeURIComponent() here.




Either way, the key will be just available by request.getParameter(key) in the servlet.



See also:




[#97751] Thursday, January 21, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rayvenc

Total Points: 666
Total Questions: 125
Total Answers: 99

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
;