MongoDB Basic Series-database query data return to the foreground JSP (ii)

Source: Internet
Author: User
Tags mongodb

On the blog discussed, the database query data returned to the foreground JSP. The blog mainly uses Ajax calls to display a JSON string to get one of these fields, assigned to one of the controls in the interface.

That this blog, we explain, the backstage list pass JSP display.

List delivery interface, what we used to do in the past. A foreach El expression. or Java code.

So how do you show the list in JSON format itself?

It is obvious that an El form and Java code are not appropriate in the form. So we continue to use Ajax to display.

One: For those who do not use the foreground frame: it is our ordinary table, in the end how to display the list in tabular form.

OK, the scenario is as follows: dynamically generating tables.

The JS code is as follows: The demo uses a button to trigger, of course can initialize in the body $ (function () {//Dynamic generation table});

I nested the table in the DIV:

<body>
	<input type= "button" value= "test specific data with Ajax" onclick= "Testajax ()"/> <div id=
	"TestTable" ></div>
   </body>
Testajax () JS is as follows:

	function Testajax () {var _url = "http://localhost:8080/testmongodb/mongodb/"; Jquery.ajax ({url: _url, type: "Get", DataType: "JSON", Success:function (d) {alert (json.stringify
		        	(d));
			    Dynamically Generate table Var mongotable=$ ("<table border=\" 1\ "></table>"); 
			   Mongotable.appendto ("#testtable");
		                        for (Var o in D) {//Generate TR, add to table var tr=$ ("<tr></tr>");
					Tr.appendto (mongotable);
					Generate TD var Td_id=$ ("<td width=\" 150\ ">" +d[o].id+ "</td>");
					var td_name=$ ("<td width=\" 150\ ">" +d[o].name+ "</td>");
					var td_city=$ ("<td width=\" 150\ ">" +d[o].address.city+ "</td>");
					
					var td_code=$ ("<td width=\" 150\ ">" +d[o].address.code+ "</td>");
					Add TD to TR Td_id.appendto (TR);
					Td_name.appendto (TR);
					Td_city.appendto (TR);
				Td_code.appendto (TR);
			Alert ($ ("#testtable"). html ());
	}
		}); }
As for the style, you can add in JS according to their own needs ha.

The background list is as follows:

[{"_id": {"$oid": "52564aa6b16b9c6f728c0cf8"}, "id": 1, "name": "Xiaoming", "address": {"City": "Beijing", "code": "065000"}}, {"_id": {"$oid": "52566683B16BE14866E9BDC5"}, "id": 2, "name": "Xiao Hong", "address": {"City": "Beijing "," Code ":" 065000 "}}]
The page is as follows:

Second: Use the foreground frame: for example, Ligerui in the grid display: (Premise: JS, CSS has been introduced)

The grid code is as follows:

	$ (function () {
		 $ (' #test '). Ligergrid {
			 columns:[ 
				{display: ' id ', Name: ' ID ', Width: '} ',
				{display: ' Names ', Name: ' Name ', Width: ',
				{display: ' City ', Name: ' Address.city ', Width: ' n ', ',
				{display: ' Zip ', name: ' Address.code ', Width: ' rownumbers:true '}
				],
			 width:
			 ' 80% ',
			 height: ' n ',
			 URL: ' http:// localhost:8080/testmongodb/mongodb/'
		 });
	

Where test is the ID of the DIV:

<body>
	<input type= "button" value= "test specific data with Ajax" onclick= "Testajax ()"/>
	<!--test grid, multi-line data >
	<div id= "test" ></div>	
    </body>
But you will find that even though the data is displayed in the background, the grid cannot be displayed. Why, Why?

That must be the grid. The display data source format does not match the list format given for JSON.

This is unique to grid in Ligerui, see the corresponding API will find that the data source of the grid is the default data format, is {rows:[]}

But our backstage list format is as follows:

[{"_id": {"$oid": "52564aa6b16b9c6f728c0cf8"}, "id": 1, "name": "Xiaoming", "address": {"City": "Beijing", "code": "065000"}}, {"_id": {"$oid": "52566683B16BE14866E9BDC5"}, "id": 2, "name": "Xiao Hong", "address": {"City": "Beijing "," Code ":" 065000 "}}]
Just add rows to the front: you can simulate this data in JS

var data={rows:[{"_id": {"inc": 1921780984, "machine": -1318347665, "new": false, "time": 1381386918000, "Timesecond" : 1381386918}, "id": 1, "name": "Xiaoming", "address": {"City": "Beijing", "code": "065000"}},{"_id": {"inc": 1726594501, " Machine ": -1318330040," new ": false," time ": 1381394051000," Timesecond ": 1381394051}," id ": 2," name ":" Little Red "," address ": {" City ": Beijing", "code": "065000"}}
	$ (function () {
		 $ ("#test"). Ligergrid ({
			 columns:[ 
				{display: ' Id ', Name: ' ID ', Width: '
				{display: ' name ', Name: ' Name ', Width: '
				{display: ' City ', Name: ' Address.city ', Width: ' Address.code '},
				{display: ' Zip code ', Name: ' Rownumbers:true ', Width: ' P '}
					],
			 width: ' 80% ',
			 height: ' data:data ',
			//url: ' http://localhost:8080/testmongodb/mongodb/'
		 };
	};
The results are as follows:

Of course you can get data and then, on this basis, rows:[{]}

Of course, you can also return to the foreground response, splicing rows

Package com.mongo.servlet;
Import java.io.IOException;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Net.sf.json.JSONArray;
Import Net.sf.json.JSONObject;
Import Com.mongo.dao.EntityTest; public class Entityservlet extends HttpServlet {@Override protected void doget (HttpServletRequest request, HttpServlet
		Response Response) throws Servletexception, IOException {System.out.println ("doget ...");
	        	try {List list=new entitytest (). SelectAll ();
	              Response.setcharacterencoding ("UTF-8");
		Mainly used in the grid form of Ligerui, the default is rows Initjsonlist (request,response,list);
		catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); } @Override protected void DoPost (HttpServletRequest req, HttpServletResponse RESP) throws Servletexception, IOException {//TODO auto-generated Method Stub doget (req, resp); } protected void Initjsonlist (HttpServletRequest request, httpservletresponse response, List list) {map map = new Ha
		Shmap ();
		Map.put ("Rows", list);
		Jsonobject jsonobject = jsonobject.fromobject (map);
			try {response.setcharacterencoding ("utf-8");
			Response.getwriter (). Write (jsonobject.tostring ());
		System.out.println (Jsonobject);
		catch (IOException e) {System.out.println (e.tostring ());
 }
	}
}

Use the Jsonobject object for conversion.

For other Ligerui presentations, you don't have to use Jsonobject or Jsonarray to convert them, because they're JSON-formatted.

Of course, the conversion is no harm, but the transformation after all the different format, but does not affect, because the user's properties will not change, the impact is Mogodb unique _id properties.

{"Rows": [{"_id": {"inc": 1921780984, "machine": -1318347665, "new": false, "time": 1381386918000, "Timesecond" : 1381386918}, "id": 1, "name": "Xiaoming", "address": {"City": "Beijing", "code": "065000"}},{"_id": {"inc": 1726594501, " Machine ": -1318330040," new ": false," time ": 1381394051000," Timesecond ": 1381394051}," id ": 2," name ":" Little Red "," address ": {" City ":" Beijing "," code ":" 065000 "}}]}
OK, so far, a certain field as well as the form of the basic ability to achieve the way has been described.

These two blog entries are made with a single project, but are demonstrated in various ways, through annotations.

In this tip: instead of Ligerui, use the array form directly [], do not use the rows:[] format. But for other frameworks, such as Ext,easyui, they all have their own data source formats, but certainly, the backend is still a JSON string.

Project demo, click I download

Related Article

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.