开发者

dropdowllist selected item from javascript to servlet

开发者 https://www.devze.com 2022-12-24 14:41 出处:网络
Is it possible to get the value from a JavaScript variable and use this value in a Java Servlet? I have read up on this but all I have found is getting the JavaScript value through a form submit.

Is it possible to get the value from a JavaScript variable and use this value in a Java Servlet? I have read up on this but all I have found is getting the JavaScript value through a form submit.

What I need is:

  • I have a html 开发者_运维技巧select combo box.
  • I need to extract the selected value from this and use this value to query a database.

Is this possible?


Well, the JavaScript runs on the client and the servlet runs on your server. So you do need to send the value to your server somehow. The two (typical) ways to do so is using a form submit, or Ajax. Since you mention the value comes from a select box I assume you want to update something on the page when the user changes selection, using Ajax would probably be what you want.

Unless the amount of data needed to update is really large, likely to change often, or your intended client is really limited in bandwidth or computing power (like mobile devices), you may allso embed all the data needed on the page and selectively hide and show the data based on the selection without using a server call. If this is possible in your scenario it's more likely to feel fast and responsive than using Ajax.


You can use AJAX request to post client side value to the server. Because AJAX is a pain without any javascript library due to cross-browser issues, this example uses popular jQuery library.

HTML:

<form id="example-form" action="/path/to/servlet" method="post">
    <select> .... </select>
    <div class="result"> The result from server is displayed here. </div>
</form>

Javascript:

$(function() {
    var f = $('#example-form');
    $('select', f).change(function() {
        $('.result', f).html('Wait...').load(f.attr('action'), f.serialize());
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号