An example of jQuery's Ajax application (I)

Source: Internet
Author: User

The lack of JavaScript skills has led to a long time of deprecated front-end interaction processing. Looking at the popularity of JavaScript in the TOP programming language rankings, coupled with the increasing user experience of many websites, JavaScript is indispensable.

To put it bluntly, the reason why developers have been cold on JavaScript for many years is that JavaScript cannot be controlled after all. However, there is always no way to escape. To develop websites with poor interaction, the background processing is awesome and cannot attract users. With the development of the Internet and Web, surfing on the internet is no longer a simple way to get information. Information is more integrated into personal emotions, self-media, community, and group elements, the integration of these elements naturally requires more user-friendly interactive services.


With this in mind, the emergence of more and more websites with good results from multiple sources has emerged.


The following example shows a simple data operation, which is completed entirely through Ajax.

1. database table structure:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/111301B31-0.png "title =" Account.png "alt =" 161635128.png"/>

2. entity class: Account (see database table structure)

3. JDBC for data source obtaining)

4. Database Operation CRUD

5. Service class ActionServlet for processing Ajax requests

JQuery provides the following Ajax functions:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/111301AQ-1.png "title =" jqueryAjaxMethod.png "alt =" 162119760.png"/>

$. Ajax (options) is the underlying implementation of Ajax in jQuery. This method is used in the following example.

  • Test page

    650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1113013053-2.png "title =" Page.png "alt =" 162339804.png"/>

  • Code:

    Page code:

    <Body> <center> <div> <label id = "l_a_name"> Name: </label> <input type = "text" id = "a_name" name = "a_name"/> <br/> <label id = "l_a_feeling"> mood: </label> <br/> <textarea rows = "10" cols = "30" id = "a_feeling" name = "a_feeling"> </textarea> <div> <label id = "msg"> </label> </div> <span> <button id = "show" name = "show" value = "show "<span> <button id =" add "name =" add "value =" add "<span> <label id =" l_a_id "> No: </label> <input type = "text" id = "a_id" name = "a_id"/> <button id = "update" name = "update" value = "update" </span> <button id = "del" name = "del" value = "delete" </span> <button id = "query" name = "query" value = "query" </span> </div> <span id = "v_a_id"> </span> <span id = "v_a_name"> </span> <span id = "v_a_feeling"> </span> <span id = "v_a_time"> </span> </div> <div id = "divs" align = "center"> </div> </center> <div> URL: <input type = "text" id = "url" name = "url"/> <input type = "button" id = "get" value = "LOAD"/> <div id = "urlcontent"> </div> <input id = "wether" type = "button" value = "retrieve JSON data"/> <div id = "loadMsg"> Please wait, loading data... </div> <div id = "imageDiv"> </div> </body>

    Description: Ajax is used to process, remove form tags, submit buttons, and other elements.

  • Ajax processing:

    Add information, query all information, delete the specified number information, update the specified number information, and query the specified number information.

  • Code:


    $ (Document ). ready (function () {$ ("# divs "). hide (); $ ("# urlcontent "). hide (); $ ("# loadMsg "). hide () ;}) function show () {$. ajax ({global: true, type: 'post', url: "control", data: {method: 'show',}, success: function (data) {var divNode = $ ("# divs"); divNode.html (""); if (data! = "Null") {var o = eval ("(" + data + ")"); var title = $ ("<div>"); title. html ("| <span> NO. </span> | <span> name </span> | <span> mood </span> | <span> release time </span> | "); title. appendTo (divNode); $. each (o, function (I, n) {var div =$ ("<div>"); var span = "|" $. each (n, function (pro, val) {span = span + "<span>" + val + "</span> |" ;}) div.html (span ). appendTo (divNode) ;}) divNode. show ();} else {$ ("# msg" example .html ("no data mail Information ") ;}}) ;}function add () {$ (" # divs "). hide (); var a_name = $ ("# a_name "). val (); var a_feeling = $ ("# a_feeling "). val (); if (a_name = "" | a_feeling = "") {alert ("the input information cannot be blank! "); Return;} $. ajax ({type: 'post', url: "control", data: {method: 'add', a_name: a_name, a_feeling: a_feeling}, success: function (data) {$ ("# msg" ).html (data); $ ("# v_a_name" ).html (a_name); $ ("# v_a_feeling" ).html (a_feeling );}});} function update () {$ ("# divs "). hide (); var a_id = $ ("# a_id "). val (); var a_name = $ ("# a_name "). val (); var a_feeling = $ ("# a_feeling "). val (); if (a_id = ""&& A_name = "" & a_feeling = "") {alert ("the input number or information cannot be blank! "); Return;} $. ajax ({type: 'post', url: "control", data: {method: 'update', a_name: a_name, a_feeling: a_feeling, a_id: a_id}, success: function (data) {$ ("# msg" ).html (data); $ ("# v_a_id" ).html (a_id); $ ("# v_a_name" ).html (a_name ); $ ("# v_a_feeling" ).html (a_feeling) ;}});} function del () {$ ("# divs "). hide (); var a_id = $ ("# a_id "). val (); if (a_id = "") {alert ("the input number cannot be blank! "); Return;} $. ajax ({type: 'post', url: "control", data: {method: 'delete', a_id: a_id}, success: function (data) {$ ("# msg" ).html (data) ;}});} function query () {var a_id = $ ("# a_id "). val (); if (a_id = "") {alert ("the input number cannot be blank! "); Return;} $. ajax ({type: 'post', url: "control", data: {method: 'query', a_id: a_id}, success: function (data) {var divNode = $ ("# divs"); divNode.html (""); if (data! = "Null") {var o = eval ("(" + data + ")"); var title = $ ("<div>"); title. html ("| <span> NO. </span> | <span> name </span> | <span> mood </span> | <span> release time </span> | "); title. appendTo (divNode); $. each (o, function (I, n) {var div = $ ("<div>"); var span = "|"; $. each (n, function (pro, val) {span = span + "<span>" + val + "</span> |" ;}) div.html (span ). appendTo (divNode) ;}) divNode. show () ;}else {$ ("# msg" ).html ("no data information ");}}});}

    Note: The URL submitted by Ajax is the Servlet program that processes the business.

  • Servlet program code:

    Package com. ajax. test; import java. io. IOException; import java. util. calendar; import java. util. date; import java. util. list; import javax. servlet. servletException; import javax. servlet. annotation. webServlet; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; @ WebServlet ("/ActionServlet") public class ActionServlet extends HttpServ Let {private static final long serialVersionUID = 1L; private DAO dao = new DAO (); private Account account Account; public ActionServlet () {super ();} protected void doGet (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {doPost (request, response);} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOE Xception {response. setCharacterEncoding ("UTF-8"); String method = request. getParameter ("method"); if (method. equals ("add") {String a_name = request. getParameter ("a_name"); String a_feeling = request. getParameter ("a_feeling"); Date a_time = Calendar. getInstance (). getTime (); account = new Account (); account. setA_name (a_name); account. setA_feeling (a_feeling); account. setA_time (a_time); int result = Dao. add (account); if (result = 1) {response. getWriter (). print (a_time + "" + a_name + "publish information successful! ");} Else {response. getWriter (). print (a_time +" "+ a_name +" failed to publish information! ") ;}} If (method. equals ("delete") {int a_id = Integer. parseInt (request. getParameter ("a_id"); account = new Account (); account. setA_id (a_id); int result = dao. delete (account); if (result = 1) {response. getWriter (). print ("Message deleted! ");} Else {response. getWriter (). print (" An error occurred while deleting the information! ") ;}} If (method. equals ("update") {int a_id = Integer. parseInt (request. getParameter ("a_id"); String a_name = request. getParameter ("a_name"); String a_feeling = request. getParameter ("a_feeling"); Date a_time = Calendar. getInstance (). getTime (); account = new Account (); account. setA_id (a_id); account. setA_name (a_name); account. setA_feeling (a_feeling); account. setA_time (a_time); int result = dao. u Pdate (account); if (result = 1) {response. getWriter (). print (a_time + "" + a_name + "Update successful! ");} Else {response. getWriter (). print (a_time +" "+ a_name +" failed to update information! ") ;}} If (method. equals ("query") {int a_id = Integer. parseInt (request. getParameter ("a_id"); Account account = dao. queryById (a_id); if (account! = Null) {String json = objctToJson (account); StringBuilder sb = new StringBuilder (); sb. append ("{'1':"); sb. append (json); sb. append ("}"); response. getWriter (). print (sb. toString ();} else {response. getWriter (). print ("null") ;}} if (method. equals ("show") {List <Account> accountList = dao. query (); StringBuilder sb = new StringBuilder (); sb. append ("{"); for (int I = 0, j = accountList. size (); I <j; I ++) {Account account Account = accountList. get (I); sb. append (I); sb. append (":"); sb. append (objctToJson (account); if (I! = J-1) {sb. append (",") ;}} sb. append ("}"); response. getWriter (). print (sb. toString () ;}}/*** convert object information to JSON data * @ param account * @ return */private String objctToJson (Account account) {StringBuilder sb = new StringBuilder (); sb. append ("{"); sb. append ("'A _ id': '" + account. getA_id () + "',"); sb. append ("'A _ name': '" + account. getA_name () + "',"); sb. append ("'A _ feeling ':'" + account. getA_feeling () + "',"); sb. append ("'A _ time': '" + account. getA_time () + "'"); sb. append ("}"); return sb. toString ();}}


  • The following is a test:

    650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/111301K14-3.png "style =" float: none; "title =" Mustang red dust "alt =" 163908535.png"/>

    650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1113012564-4.png "style =" float: none; "title =" Mustang red dust "alt =" 163909105.png"/>

    So far: jQuery's underlying Ajax implementation operations implement database CRUD operations without refreshing, and the entire process is completed on an HTML page.

  • $. Get (), $. the post (), load () method is in the $. is encapsulated based on ajax. ajax) is set to the first layer, so these methods are the second layer, $. getScript () and $. the getJSON () method is the third layer.

Since the above post write code, write some long, for the example of the third layer see Article 2: http://aiilive.blog.51cto.com/1925756/1304356

This article is from the "wild horse red dust" blog and will not be reposted!

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.