While working with Confluence I found 2 ways to make Ajax requests:
- make requests to servlets
- make JSON requests to XWork actions
The implementation is very simple and requires only to properly configure the servlet:
- edit your atlassian-plugin.xml file and add a servlet definition, see Developer documentation for further info
- implement AjaxListServlet class, I prefer to generate HTML code directly, but you can generate JSON array as well
- put comboboxes for city and department in .vm page
- and, finally, attach javascript to city combobox. here is a JQuery code
<servlet name="Ajax List Servlet"
key="ajaxListServlet"
class="dot.userinfo.users.servlets.AjaxListServlet">
<description>Ajax List Servlet</description>
<url-pattern>/getlist/</url-pattern>
</servlet>
public class AjaxListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
String list = req.getParameter("list");
if ("dep".equalsIgnoreCase(list)) {
String cityName = req.getParameter("city");
// generate departments list HTML
StringBuffer sb = new StringBuffer();
sb.append("<option value='' selected></option>");
try {
for (DepartmentInfo dep : getDepartmentsDao().
getByCityName(cityName)) {
sb.append("<option>");
sb.append(dep.getName());
sb.append("</option>");
}
} catch (Exception e) {
// handle exception
}
resp.getOutputStream().print(sb.toString());
return;
}
}
private DepartmentsDao getDepartmentsDao() {
return DaoFactory.getDepartmentsDao();
}
}
#tag( Select "id=city" "name='user.city'"
"list=citiesDao.all"
"listKey=name" "listValue=name"
"emptyOption='true'" "theme='notable'" )
#tag( Select "id=department" "name='user.department'"
"list=departmentsDao.all"
"listKey=name" "listValue=name"
"emptyOption='true'" "theme='notable'" )
jQuery(function($) {don't forget to include JQuery in your .vm page header
$("document").ready(function () {
$("#city").change(function() {
var cityName = $("#city option:selected").val();
$.get("/plugins/servlet/getlist/",
{list: "dep", city: cityName}, function(data) {
$("#department").html(data);
});
});
});
});
<html>
<head>
<title>...</title>
#requireResource("confluence.web.resources:jquery")
</head>
No comments:
Post a Comment