Ajax invoke background action return Jsonarray (Jsonobject) Type implementation JSP drop-down list dynamic display

Source: Internet
Author: User

First, describe

Now there is a JSP page has a school and a class drop-down list, only after selecting the school to pop up the class list, so the use of Ajax technology to return a ArrayList type of key value pairs displayed in the class list, effect 1 shows:



Second, the source code

1, main.jsp main source code

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><% @taglib prefix=" s "uri="/struts-tags "%><%@ taglib prefix=" C "uri= "Http://java.sun.com/jsp/jstl/core"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
2, JSP introduced in the same directory down with the Ajax Boardcollect.js source code

Create request Var http_request;function createxmlhttprequest () {http_request=false; if (window.  XMLHttpRequest) {http_request=new XMLHttpRequest (); Initialize Http_requestif (http_request.overridemimetype) {http_request.overridemimetype ("text/html");}} else if (window.  ActiveXObject) {try{http_request=new ActiveXObject ("msxml2.xmlhttp");  Create XMLHttpRequest object in IE, new version ie}catch (e) {try{http_request=new ActiveXObject ("Microsoft.XMLHTTP"); Create XMLHttpRequest object in IE old version Ie}catch (e) {}}}if (!http_request) {Window.alert ("Cannot create XMLHttpRequest object instance"); return false;} Show Class list Var comlist;function showclass () {//click on "School" to show the list of all classes under the school//window.alert ("Showclass"); var school = document.getElementById ("Schoolcircle"). Value;//alert (school); if (school = = 0) {var htmllist = ' <select name= ' Classcircle "id=" classcircle "> ' + ' <option value=" 0 ">--class list--</option> ';d Ocument.getelementbyid (" Classcircle "). InnerHTML = Htmllist;} else {showoptions ("findclasslist1.action?school=" + School);} Showcomments ("/modules/forum/frOntforum/forumall/boardcollect.action?mcpforumboard.boardid= "+id);} function showoptions (URL) {createxmlhttprequest ();//window.alert (URL);//Specify handler event Solver!!! Http_request.onreadystatechange=processrequest;  Http_request.open ("GET", url,true); Http_request.send (NULL); }//function ProcessRequest () {//window.alert (http_request.readystate) for processing return information, if (http_request.readystate==4) {// Window.alert (Http_request.status); if (http_request.status==200) {var classlist = eval (' +http_request.responsetext + ') ');//var classlist = Com.classlist;//alert (classlist.length); var htmllist = ' <select name= ' classcircle ' id= '  Classcircle ">"; htmllist + = ' <option value= "0" >--class list--</option> '; for (var i = 0; i < classlist.length; i++) {var circle = Classlist[i];//alert (circle["circle_id"]); Htmllist + = ' <option value= ' ' +circle[' circle_id ']+ ' " > ' + circle["circle_name"] + ' </option> ';} document.getElementById ("classcircletd"). InnerHTML = Htmllist;}}}


3, the boardcollect.js in the AJAX Call Background action processing class source code

Find all classes in the selected school public list<map> FindClassList1 () {httpservletresponse response;         Response=servletactioncontext.getresponse ();         Response.setcontenttype ("Text/json;charset=utf-8");         Response.setheader ("Cache-control", "No-cache");         Response.setheader ("Pargma", "No-cache");        PrintWriter Out;try {out = Response.getwriter ();    Jsonarray returnarticles = new Jsonarray (); if (school = = NULL | | school.length () = = 0) {return null;} else {String sql = "Select circle_id, Circle_name from Dersp_ci Rcle,dersp_school_class_relation "+" where class_id=circle_id and school_id= "+ school; SYSTEM.OUT.PRINTLN ("sql:" +sql); list<map> list = jdbctemplate.queryforlist (sql), for (int i = 0; i < list.size (); i++) {Jsonobject js = new               Jsonobject (); try {js.put ("circle_id", List.get (i). Get ("circle_id")), Js.put ("Circle_name", List.get (i). Get ("Circle_name")); Returnarticles.put (JS);} catch (Jsonexception e) {//TODO auto-generated CatCH Blocke.printstacktrace ();}         }}out.write (Returnarticles.tostring ()); Out.close (); } catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return null;}


Iii. Summary

1, a JSP page onchange or onclick event call JS a method, the method uses Ajax technology to dynamically invoke data in the database, and asynchronously write back to a jsonarray, according to the option property in select to display the retrieved data;

2. If you want to return an array of type map (multiple data) after calling Ajax, you need to use the Jsonarray type, construct each map as a jsonobject type and add it to the Jsonarray array to asynchronously write back to the JSP page;

3. How do you only want to return a key-value pair for a map type from action (such as the number of count (*) records), you can only use the Jsonobject object to return a single piece of data and display it.

Ajax invoke background action return Jsonarray (Jsonobject) Type implementation JSP drop-down list dynamic display

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.