Jquery Ajax access servlet to process JSON data

Source: Internet
Author: User

Front-end JSP page:

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <% string Path = request. getcontextpath (); string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/"; %> <! Doctype HTML> 

A servlet in the background obtains data from MySQL and processes it as a jsonarray

package com.action;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;public class JsonServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { Toto toto = new Toto();toto.selectAllUsers();JSONArray json = JSONArray.fromObject(toto.getUsers()); response.setCharacterEncoding("utf-8");PrintWriter pw = response.getWriter();pw.print(json);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}

Effect after running:

Additional: You can write jquery asynchronous data retrieval as follows: (this method is recommended, which is relatively standard)

 $.getJSON("servlet/JsonServlet",function(htmlobj){ $(".sj").empty();       var html = '<table>';          $.each(htmlobj,function(entryIndex,entry){       html += '<tr><td>'+entry['id']+'</td></tr>';     });          html += '</table>';                        $(".sj").append(html);   });}

You can also write as follows:

$.ajax({url:'servlet/JsonServlet',type:'post',success:function(msg){var htmlobj = jQuery.parseJSON(msg);var html = '<table>';$.each(htmlobj,function(entryIndex,entry){       html += '<tr><td>'+entry['id']+'</td></tr>';    });html += '</table>';                        $(".sj").html(html);  }});

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.