从JavaScript调用/ jQuery的在JSP后端Java方法 [英] Calling a backend Java method from JavaScript/jQuery in JSP
问题描述
我有一个JSP,其中有包含实体类型的名称的选择
列表。当我选择一个实体那种我需要填充另一个选择
列表与选定的实体类型的字段名。为此,我呼吁的onchange
事件的JavaScript函数。
I have a JSP in which there is a select
list containing entity kind names. When I select an entity kind I need to populate another select
list with the field names of the selected entity kind. For that I call a JavaScript function on the onchange
event.
在JavaScript方法,我需要调用后台的方法返回一个的ArrayList
包含所选实体类型的字段名。
In the JavaScript method I need to call a method in the backend that returns an arraylist
that contains the field names of the selected entity kind.
我如何调用使用和不使用Ajax的方法?另外我如何动态填充第二个选择列表中的的ArrayList
?
How do I call the method with and without Ajax? Also how do I populate the second select list dynamically with the arrayList
?
推荐答案
我将介绍两种方法去:有/无AJAX
I'll describe two ways to go: with/without AJAX.
-
如果你想要做一个同步表单提交你需要附加
的onchange
事件,你的第一个选择
元素:
If you want to do a synchronous form submit you'll need to attach
onchange
event to your firstselect
element:
<select name="select-one" id="select-one" onchange="this.form.submit()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
在做这样一来,该表格会和第一选择的选项将作为的request.getParameter(选择一)
,在此基础上你会提供数据的第二个下拉人口,通常转发至JSP。
When done this way, the form will be submitted and first select option will be available as request.getParameter("select-one")
, based on which you'll provide data for second dropdown population, typically forwarding to a JSP.
如果您想通过AJAX 检索列表并重新填充另一个下拉菜单,你可以发送一个AJAX请求和处理返回的数据的回调函数:
If you want to retrieve a list via AJAX and repopulate another dropdown, you can send an AJAX request and handle returned data in a callback function:
var val = $('#select-one option:selected').val();
$.ajax({
url: "servletURL",//servlet URL that gets first option as parameter and returns JSON of to-be-populated options
type: "POST",//request type, can be GET
cache: false,//do not cache returned data
data: {one : val},//data to be sent to the server
dataType: "json"//type of data returned
}).done(function(data) {
var second = $("#select-two");
$.each(data, function() {
options.append($("<option />").val(this.value).text(this.label));
});
});
在做这样一来,第二个下拉将不刷新页面重新填充。
When done this way, the second dropdown will be repopulated without page refresh.
这篇关于从JavaScript调用/ jQuery的在JSP后端Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!