How does ajax get database data?

Database is a warehouse for organizing, storing and managing data according to data structure. It was born 50 years ago, with the development of information technology and market, especially after the 1990s, data management is not It's just about storing and managing data, and turning it into a variety of data management methods that users need. There are many types of databases, ranging from the simplest tables that store various data to the large database systems that can store massive amounts of data. In the information society, the full and effective management and utilization of various information resources is a prerequisite for scientific research and decision management. Database technology is the core part of various information systems such as management information systems, office automation systems, and decision support systems. It is an important technical means for scientific research and decision management.

Ajax dynamically retrieves data from the database

In this article, an example will be given to introduce three methods for obtaining data from the server using AJAX technology. This example is very simple, is the two selection boxes ("select" tab in html), after selecting one of the first select, it will get some data from the server and load it into the second select.

How does ajax get database data?

Method 1: Obtain data in XML format from the server

The easiest way to get data from the server is to add a certain format of data on the server, usually in XML format, and then use XMLDocument or other technology to read the data on the server and generate options in the "select" tag. Formatted text ("opTIon" tag). The following addOpTIons function is the core function of this example, it is responsible for generating the "opTIon" tag in the "select" tag based on the data obtained from the server. The method used here is to use the innerHTML attribute of the "select" tag (firefox only). If it is IE, use the outerHTML attribute (the innerHTML attribute of the "select" tag in IE has some minor bugs, the reader can try Use the innerHTML property in IE to see what happens.) The implementation code of the addOpTIons method is as follows:

// select represents the "select" object, xml represents the XMLDocument object

Function addOptions(select, xml)

{

If(select)

{

Var options = "";

For(var i = 0; i " xml.childNodes[0].childNodes.length ; i++)

{

If(xml.childNodes[0].childNodes[i].nodeName == "list")

{

Var s = "";

If(isIE())

s = xml.childNodes[0].childNodes[i].text;

Else

s = xml.childNodes[0].childNodes[i].textContent

Options += "option value='" + s + "'"";

Options += s;

Options += "/option"

}

}

Var id = select.id;

If(isIE())

select.outerHTML = ""SELECT id='" + id + "' onchange='onChange(this)'" + options + "/SELECT";

Else

select.innerHTML = options;

}

}

The onReadState function will be called when the XMLHttpRequest object is accessed asynchronously on the server. When the readyState is 4, it means that the XML data is successfully returned from the server. The implementation code for this function is as follows:

// myRequest represents the XMLHttpRequest object, and selectId represents the id attribute value of the "select" tag.

Function onReadyState(myRequest, selectId)

{

If(myRequest.readyState == 4) // 4 means that the corresponding information is successfully obtained.

{

Try

{

Var xml = myRequest.responseXML; // get the XMLDocument object

Var kind = document.getElementById(selectId); // get the "select" object

addOptions(kind, xml); // Add the "option" tag to the "select" tag

}

Catch(e)

{

Alert("onReadyState:" + e);

}

}

}

The getData function is responsible for sending requests to the server and setting up asynchronous events. The implementation code is as follows:

Function getData(url, selectId)

{

Var myRequest = getXMLHTTPRequest(); // Get an XMLHttpRequest object

If(myRequest)

{

myRequest.onreadystatechange = function() // Receive the event function that gets the data state

{

onReadyState(myRequest, selectId);

}

Try

{

myRequest.open( "post", url, true);

}

Catch(e)

{

Alert(e);

}

Try

{

myRequest.send("");

}

Catch(e)

{

Alert(e);

}

}

}

Now the core code of this example has been implemented. The next step is to get the data of the first "select" tag from the server when loading it in html and load it into the first "select" tag. Let's take a look at this static html code.

"! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"html"

"head"

"title" / "title"

"meta http-equiv="Content-Type" content=“text/html; charset=UTF-8”

"script type="text/javascript" src=“myscript.js”

"/script"

/head

"body"

"select id="bigKind" onchange=“onChange(this)” 》

"/select"

"select id="smallKind"

"/select"

"/body"

"/html"

As can be seen from the above code, the two "select" tags are bigKind and smallKind, respectively, there is no "option" tag, because the "option" tag is dynamically loaded in javascript. Let's first load the data in bigKind.

Window.onload = onLoad

Function onLoad()

{

Try

{

getData("./GetXML", "bigKind");

}

Catch(e)

{

Alert("onLoad:" + e);

}

}

Among them, GetXML is a Servlet program (readers can replace it with other server programs, such as asp.net, php). Here is the implementation code for this GetXML program:

Package servlet;

Import java.io.*;

Import javax.servlet.*;

Import javax.servlet.http.*;

Import database.MyData;

Public class GetXML extends HttpServlet

{

Protected void processRequest(HttpServletRequest request, HttpServletResponse response)

Throws ServletException, IOException

{

response.setContentType("application/xml;charset=UTF-8");

PrintWriter out = response.getWriter();

Try

{

String s = request.getParameter("kind");

Out.println("data"");

If (s == null)

{

For (String key : MyData.data.keySet())

{

Out.println("list" + key + "/list");

}

} else

{

s = java.net.URLDecoder.decode(s, "UTF-8");

System.out.println(s);

java.util.List "String" smallKind = MyData.data.get(s);

If (smallKind != null)

{

For (String kind : smallKind)

{

Out.println("list" + kind + "/list");

}

}

}

Out.println("/data"");

} finally

{

Out.close();

}

}

Protected void doGet(HttpServletRequest request, HttpServletResponse response)

Throws ServletException, IOException

{

processRequest(request, response);

}

Protected void doPost(HttpServletRequest request, HttpServletResponse response)

Throws ServletException, IOException

{

processRequest(request, response);

}

Public String getServletInfo()

{

Return "Short description";

}

}

Regardless of whether the reader will be java or servlet, you can see from the processRequest method in this program that the request parameter kind will be obtained first. If this parameter does not exist, the data needed by bigKind will be returned and returned in xml format, similar to The following format:

Data

"list" data1 "/list"

"list" data2 "/list"

"/data"

If the kind parameter exists, the data required by the second "select" tag (smallKind) is queried in MyData.data. Data is a Map type. For convenience, this example does not use a database, but instead defines a static Map type variable in the MyData class. The implementation code of MyData is as follows:

Package database;

Import java.util.*;

Public class MyData {

Public static Map "String, List "String"" data;

Static {

Data = new HashMap "String, List "String"" ();

List "String" eProducts = new LinkedList "String" ();

eProducts.add("Mobile");

eProducts.add("Digital/IT");

eProducts.add("Home Appliances");

eProducts.add("computer");

Data.put("Consumer Electronics", eProducts);

List "String" goods = new LinkedList "String" ();

Goods.add("makeup");

Goods.add("health");

Goods.add("toy");

Goods.add("office/stylish");

Goods.add("children's shoes");

Goods.add("Other");

Data.put("daily department store", goods);

List "String" books = new LinkedList "String" ();

Books.add("fiction");

Books.add("anime");

Books.add("Economy");

Books.add("law");

Books.add("computer");

Books.add("English");

Books.add("Communication");

Books.add("Other");

Data.put("book", books);

}

}

The key value in the data variable is the value in bigKind, and the value corresponding to each key (a List "String" object is a list of values ​​in smallKind). Let's update the smallKind tag when the first "select" tag bigKind changes. The code for the onchange event function of "select" is as follows:

Function onChange(obj)

{

Try

{

getData(encodeURI(en.zip("./GetXML?kind=" +obj.options[obj.selectedIndex].value)), "smallKind");

}

Catch(e)

{

Alert(e);

}

}

This function is the onchange event function of the "select" tag. Obj means the "select" tag itself. There is only one statement in this function that has practical meaning, that is, the getData method is called. This method is similar when calling getData in the onLoad method, but only uses two encodeURI methods when transmitting the url. Since the XMLHttpRequest method sends data to the server in UTF-8, it uses two encodeURIs to send the utf-8 encoding of the %xx form to the server, and then parse it on the server. We can find the following statement in the processRequest method in GetXML:

s = java.net.URLDecoder.decode(s, "UTF-8");

Is to perform the decoding operation.

Note: If in IE, the client can encode the URL with Chinese without using encodeURI, the server does not need to decode. Chinese can still be displayed normally on the server. But in Firefox you have to encode and decode. Therefore, to cross browsers, you need to use the methods described in this article.

Method 2, directly obtain "option". . . String of /option content

The above method of obtaining data is to obtain an XML document from the server and convert it into an XMLDocument object and then parse it. Although this method is very good, it is still a bit of a hassle to manipulate the XMLDocument object. Therefore, we can directly return the "option" tag string required by the "select" tag on the server side, and then pass the string to the "select" object. innerHTML or outerHTML is fine. The server code is similar to the above implementation code. Just remove "data", then change "list" to "option" and use the following statement to set the ContentType:

response.setContentType("text/html;charset=UTF-8");

The client can obtain these texts containing "option" through the responseText property of the XMLHttpRequest object and assign it to the innerHTML or outerHTML properties. Although this method is convenient, it is not flexible. If the client does not use the "select" tag, but uses "table" or other tags to display the data, then the returned data is useless. That is convenient and flexible, it should be the method to be introduced below.

Method three, return the javascript code from the server, execute the eval function on the client

We can return a string similar to the following on the server side:

Var options = new Array();

Options.push('data1');

Options.push('data2');

Then use the eval function to execute the above string, so we can use the options array in javascript. I personally think that using arrays is easier and less code-intensive than using XMLDocuments. If you want to return more complex data, you can also use classes or other data structures in javascript. According to the above idea, the code of the new processRequest method is as follows:

Protected void processRequest(HttpServletRequest request, HttpServletResponse response)

Throws ServletException, IOException

{

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

Out.println("var options = new Array();");

Try

{

String s = request.getParameter("kind");

If (s == null)

{

For (String key : MyData.data.keySet())

{

Out.println("options.push('" + key + "');");

}

} else

{

s = java.net.URLDecoder.decode(s, "UTF-8");

System.out.println(s);

java.util.List "String" smallKind = MyData.data.get(s);

If (smallKind != null)

{

For (String kind : smallKind)

{

Out.println("options.push('" + kind + "');");

}

}

}

} finally

{

Out.close();

}

}

The client's improved addOptions function is as follows:

// javascript represents the javascript code string returned from the server

Function addOptions(select, javascript)

{

If(select)

{

If(select.id == "smallKind")

{

If(isIE())

Select.options.length = 0;

}

Var myOptions = "";

Eval (javascript); / / execute the javascript code returned from the server

For(var i = 0; i " options.length ; i++) // fetch data from the options array

{

Var s = "";

If(isIE())

{

Select.options[select.options.length] = new Option(options[i], options[i]);

}

Else

{

myOptions += "option value='" + options[i] + "'"";

myOptions += options[i];

myOptions += "/option"

}

}

}

Var id = select.id;

If(!isIE())

select.innerHTML = myOptions;

}

Another difference in the addOptions method above is the use of the options array of the "select" object in IE to add options instead of using outerHTML. The advantage of doing this is that you can get the option value of "select" in the onLoad method. If you use outerHTML when the html is not loaded, the selection in the "select" tag is still 0. In this way, you can't access the added items in "select" in the onLoad method. Of course, you can do this in the onchange event.

When using innerHTML in firefox, when the html is not loaded, as long as the "select" tag is loaded (that is, after the addOptions method is called), you can access the "option" in the "select" tag. Personally feel that this is going to be done well from IE. Figure 1 is an effect diagram of this example

How does ajax get database data?

figure 1

Switch & Socket

Switch & Socket,Sockets And Switches,Brass Plug Sockets,Light Switches And Sockets

WENZHOU TENGCAI ELECTRIC CO.,LTD , https://www.tengcaielectric.com