Translate

Saturday, March 31, 2012

jQuery, AJAX, JSON - Mofify Select Box Options


In my Struts action I populate a list, lstDataView, and then use Flexjson to serialize:

public String appTableChange() throws Exception {
 if(request.getParameter("this.appTableID") != null){
  this.appTableID = Integer.parseInt(request.getParameter("this.appTableID"));
 }
 if(this.appTableID != null){
  SessionService.removeAttributeFromSession(request, "LstViewRecords");
  //load the list of views
  loadTableViews();
  //serialize the list
  String jsonResult = new flexjson.JSONSerializer().serialize(lstDataView);
  response.setContentType("text/javascript");
  response.getWriter().write(jsonResult);
 }
 return null;
}


Each entry in the list has two fields, ID and title. ID will be used for the key and title will be used for the value when I create the options. Here is the snippet of script from my JSP page. Using getJSON, I call the Struts action listed above. Then I iterate through the returned result to create the string of options and change the options in the select box.

$.getJSON("../AppTableChange.action", {appTableID: $(this).val(), ajax: 'true'}, function(j){
var options = '<option value=-1>Please Select</option>';
 for (var i = 0; i < j.length; i++) {
  options += '<option value="' + j[i].ID + '">' + j[i].title + '</option>';
 }
 $("select#viewID").html(options);
})

No comments:

Post a Comment

Thank you for commenting!