简体   繁体   English

如何使用ajax或jquery将选择框的值发送到servlet?

[英]How to send values of the select box to servlet using ajax or jquery?

Im new to ajax. 我是ajax的新手。 I want to redirect to servlet with the parameter value of the select box to my servlet. 我想使用选择框的参数值重定向到servlet。 This is my code and its not retrieving values when I use request.getParameter("type") it gives me a null. 这是我的代码,当我使用request.getParameter(“ type”)时,它没有检索值,它为我提供了null。

     <script>
       $(document).ready(function() {       
         $('#type').change(function() {                              
           $.get('pickasset', function(responseJson) {
             var type = $('#type').val();
            $.ajax({
                type:'POST',
                url: 'PickAssetServlet',
                data: type          
            }); 
           });
        });
      });
    </script>

    <form action="pickasset" method="post">
        <select id="type" name="type">
           <option value="Non-Sap">Non Sap</option>
           <option value="Sap">Sap</option>
        </select>
    </form>

When i change the select box, it must go to servlet and do logic there. 当我更改选择框时,它必须转到servlet并在那里执行逻辑。

像这样发送您的数据-

data: { type : type }

If you're not getting the selected option from the select field, you need to use $('#type').find(":selected").text() to retrieve the selected option. 如果没有从选择字段中获得选定的选项,则需要使用$('#type').find(":selected").text()来检索选定的选项。 val() doesn't work with select fields. val()不适用于选择字段。 Also do what pXL said because that's how you send data with jQuery ajax methods 还要执行pXL所说的,因为这就是使用jQuery ajax方法发送数据的方式

Check box value must be obtained from checkbox in the right way, as mentioned in jQuery docs ( http://api.jquery.com/val/ ), just pay attention to multiple select, you're gonna have an array of values. 如jQuery文档( http://api.jquery.com/val/ )中所述,必须以正确的方式从复选框中获取复选框的值,只是要注意多个选择,您将拥有一个值数组。 You are doing it right, according to docs. 根据文档,您做得对。

var varValue = var type = $('#type').val();

Then sending data as 'json' you will be able to read them with request.getParameter('type') 然后将数据作为“ json”发送,您将能够使用request.getParameter('type')读取它们

data: { "type" : varValue }

If you still get null, try to check if your "type" param and his value are in the request (chrome request inspector will be usefull, then check it in the debugger). 如果仍然为null,请尝试检查您的“类型”参数及其值是否在请求中(chrome请求检查器将很有用,然后在调试器中对其进行检查)。

.

PS 聚苯乙烯

Just check if you have something in your webapp filterchain that may wrap you request or hide some params, in some large web-app you get lost very easly. 只需检查您的webapp过滤链中是否有某些东西可以包装您的请求或隐藏某些参数,在某些大型Web应用程序中,您很容易迷路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM