Two types of data type XML and JSON usages returned by Ajax

Source: Internet
Author: User
Tags script tag

Using XML to flyer a data

First, in the Servlet class to write the data to be transmitted, dog is to simulate the content extracted from the database,

Use Response.getwrite (). Append () to return the data, note that the table header <?xml version= ' 1.0 '?> can not be written wrong, the root is unique

protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// TODO auto-generated Method Stub//response.getwriter (). Append ("Served at:"). Append (Request.getcontextpath ()); Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8");//Simulate the information extracted from the database dog d = new Dog (); D.setname ("name");d. Setzhuren ("haha");d. Setage (2);d. Setzhonglei ("AAA");//use XML to go back Response.getwriter (). Append (" <?xml version= ' 1.0 '?> ");//table Header Response.getwriter (). Append (" <dog> ");//root, is the only Response.getwriter (). Append ("<name>" +d.getname () + "</name>"); Response.getwriter (). Append ("<zhuren>" +d.getzhuren () + "</zhuren>"), Response.getwriter (). Append ("<age>" +d.getage () + "</age>"); Response.getwriter (). Append ("<zhonglei>" +d.getzhonglei () + "</zhonglei>"); Response.getwriter (). Append ("</dog>");}

On the JSP page

First, we refer to "js/jquery-1.11.1.min.js" and write a click event on the #d element, which uses the AJAX engine to process the data.

The URL is the path to the data being received, and datatype is what type of data is returned

?" XML ": Returns an XML document that can be processed with jQuery.
?" HTML: Returns plain text HTML information, and the included script tag is executed when the DOM is inserted.
?" Script ": Returns plain text JavaScript code. Results are not automatically cached. Unless the "cache" parameter is set. Note: On remote requests (not in the same domain), all POST requests are converted to GET requests. (because the script tag of the DOM will be used to load)
?" JSON: Returns the JSON data.
?" Jsonp ": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function.
?" Text ": Returns a plain text string
<script type= "Text/javascript" src= "js/jquery-1.11.1.min.js" ></script><script type= "text/ JavaScript >$. Ready (Function () {$ ("#d"). Click (function () {$.ajax ({url: "Textdog",// Accept data from Textdog servlet class Data:{},type: "POST", DataType: "xml",//return type is Xmlsuccess:function (AAA) {//Resolution returned Aaavar N = $ (AAA) . Find ("name"). Text (), var z = $ (AAA). Find ("Zhuren"). Text (), var a = $ (AAA). Find ("Age"). Text (), Var ZL =$ (AAA). Find (" Zhonglei "). Text ();//The data is displayed on the page in the element found through #u $ (" #u "). Append (" <li> "+n+" </li> "), $ (" #u "). Append (" <li > "+z+" </li> "), $ (" #u "). Append (" <li> "+a+" </li> "); $ (" #u "). Append (" <li> "+zl+" </li (> ");});}); </script>

Demo Result:

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------

Using XML to pass collections,

First, in the Servlet class to write the data to be passed, as a single basic, pay attention to the root, because there are multiple dog so to use a larger Chongwu as the root, all the dog wrapped up

protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8");//Simulate data extracted from the database dog D1 = new Dog (); D1.setname ("Day of the Day");d 1.setZhuren ("Papa");d 1.setAge (1);d 1.setZhonglei ("Teddy");D og d2 = new Dog ();d 2.setName ("Drag and Drop"); D2.setzhuren ("Tuo Tuo baba");d 2.setAge (2);d 2.setZhonglei ("Golden Hair");D og d3 = new Dog ();d 3.setName ("Van van");d 3.setZhuren ("Van van Dad"); D3.setage (3);d 3.setZhonglei ("husky");//Put d1d2d3 in list arraylist<dog> list = new arraylist<> () List.add (d1 ); List.add (D2); List.add (D3);//Use XML to transmit data to page Response.getwriter (). Append ("<?xml version= ' 1.0 '?>");//Header//root, There's more than one dog here, so we wrap it up with a bigger Chongwu response.getwriter (). Append ("<chongwu>"); Traverse for (Dog d:list) {response.getwriter (). Append ("<dog>"); Response.getwriter (). Append ("<name>" + D.getname () + "</name>"); Response.getwriter (). Append ("<zhuren>" +d.getzhuren () + "</zhuren>"); Response.getwriter (). Append ("&LT;AGE&Gt; " +d.getage () + "</age>"); Response.getwriter (). Append ("<zhonglei>" +d.getzhonglei () + "</zhonglei>" ); Response.getwriter (). Append ("</dog>");} Response.getwriter (). Append ("</chongwu>");}

In JSP, the same first introduces the jar package

First put all the dog into a dogs, equivalent to an array,

<script type= "Text/javascript" src= "js/jquery-1.11.1.min.js" ></script><script type= "text/ JavaScript >$. Ready (Function () {$ ("#d"). Click (function () {$.ajax ({url: "Textdog1", Data:{},type: "POST ", DataType:" XML ", Success:function (HHH) {//First put all the dog into dogs, equivalent to an array, not an object var dogs = $ (HHH). Find (" dog ");// TB is the jquery object found in var TB =$ ("#tb");//cyclic dogsfor (var i =0;i<dogs.length;i++) {var n = $ (dogs). EQ (i). Find ("name"). Text (); var z = $ (dogs). EQ (i). Find ("Zhuren"). Text (), var a = $ (dogs). EQ (i). Find ("Age"). text (); var lei =$ (dogs). EQ (i). Find (" Zhonglei "). Text ();//information splicing var tr =" <tr> ", tr + =" <td> "+n+" </td> "; tr + =" <td> "+z+" </td> "; TR + = "<td>" +a+ "</td>", tr + = "<td>" +lei+ "</td>"; tr + = "</tr>";//Put TR in TD for $ (TB). Append ( TR)})}) </script>

Results Demo:

 

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------

Using JSON to pass data, first import the JSON jar package, write the data to be passed in the Servlet class.

Put the dog in the JSON of Jo, then put Jo into the json of obj, and the key in Jo in the page can be directly evaluated.

protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Encoding format request.setcharacterencoding ("Utf-8"), Response.setcharacterencoding ("Utf-8"),//dog d = new Dog ();d. SetName ("drag ");d. Setzhuren (" Li-ha ");d. Setage (2);d. Setzhonglei (" golden Hair ");//Put the dog in JSON, assign it with put, key and valuejsonobject Jo = new Jsonobject (); Jo.put ("Name", D.getname ()), Jo.put ("Zhuren", D.getzhuren ()), Jo.put ("Age", D.getage ()), Jo.put ("Zhonglei", D.getzhonglei ()); In this JSON, obj, put Jo in the json,obj with jojsonobject obj = new Jsonobject () obj.put ("Dog", Jo), Response.getwriter (). Append ( Jo.tostring ());}

In the JSP, change the return data type to JSON and then display the data in the page

<script type= "Text/javascript" src= "js/jquery-1.11.1.min.js" ></script><script type= "text/ JavaScript >$. Ready (Function () {$ ("#d"). Click (function () {$.ajax ({url: "Textjson1",// Accept data from Textjson1 's servlet class Data:{},type: "POST", DataType: "JSON",//The data type returned is Jsonsuccess:function (AAA) {//data displayed in through # U find the element inside $ ("#u"). Append ("<li>" +aaa.name+ "</li>"); $ ("#u"). Append ("<li>" +aaa.zhuren+ "</li>"); $ ("#u"). Append ("<li>" +aaa.age+ "</li>"); $ ("#u"). Append ("<li>" +aaa.zhonglei+ "</li>"); }});});}); </script>

Show Results:

Two types of data type XML and JSON usages returned by Ajax

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.