Preliminary study on Ajax technology

xiaoxiao2021-03-14  194

I have not understood what the so-called Ajax technology doesn't understand. Today, I have to go to a lot of information. I also run a few examples of success, and I have a preliminary understanding. The so-called AJAX technology is actually adding an AJAX engine between servers and browsers. It is generally written in JavaScript, handles some operations that do not need to refresh the entire page, such as data verification, cascade menu, read external data, etc. The interaction of the server and the server improves the response speed. Using XHTML and CSS standardization rendering, use the DOM to dynamically display and interact, using XML and XSTL to perform data exchange and processing, use the XMLHTTPRequest object to perform asynchronous data read, using JavaScript binding and processing all data. Please note that "asynchronous" two words, this may be the essence of AJAX.

Ajax has the following advantages:

Reduce the burden on the server. The principle of AJAX is "Data by Data", which can minimize redundant requests, and the burden on the server. .. Non-refresh update page, reduce user mentality and actual waiting time. In particular, when you want to read a lot of data, you don't have a white screen like Reload. AJAX uses the XMLHTTP object to send a request and get the server response, and use the JavaScript operation DOM final update without reloading the entire page. page. Therefore, in the process of reading the data, the user faces is not a white screen, which is the original page content (you can also add a loading prompt to let the user know that the data process is read), only when the data is received. The content of the corresponding part. This update is instant, and the user can't feel almost. .. Bring a better user experience. .. You can transfer the work of some of the previous server burden to the client, using the client's idle ability to deal with the burden on the server and bandwidth, save space and broadband rental cost. .. External data can be called. .. Based on standardized and widely supported technology, you don't need to download plugins or applets. .. Further promoting the separation of the page presentation and data.

Main objects and methods of XMLHTPREQUEST:

Main method for XMLHttpRequest classes

Abort () stops the current request

getAllResponseHeaders () Returns complete Headers

GetResponseHeader () Returns a single Header

Open ("Method", "URL" [, asyncflag [, "username" ["Password"]]] Sets URLs, objects, methods, and other parameters that are unresolved requests

Send (Content) Send Request

SetRequestHeader ("Label", "Value") Sets Header and send it with the request.

The properties of the XMLHttpRequest class

OnReadyStateChange

ReadyState (0 Not initialization 1 Read 2 has been read 3 interaction 4)

ReponseText server process returned text information

Responsexml

STATUS status code

STATUTSTEXT

A simple example:

1. Servlet used to interact:

/ * * Created date 2006-3-16 *

* / package com.denny_blue.servlet;

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; / ** * @author dennis * * AJAX a simple program example, This is its servlet, call response information based on request. * /

Public class selectcityServlet Extends httpservlet {

PRIVATE STATIC FINAL Long SerialVersionuid = 3846719385151382073L;

Public selectcityServlet () {super ();

Public void destroy () {super.destroy ();

public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / xml"); response.setHeader ( "Cache-Control", "no-cache"); String state = request.getParameter ( "state"); stringbuffer sb = new stringbuffer (""); if ("zj" .Equals (state)) {sb.append (" HANGzhou Huzhou ");} else if (" zs ".equals (state)) {sb.append (" nanjing yangzhou suzhou ); } sb.append (""); PrintWriter out = response.getwriter (); out.write (sb.tostring ()); out.close ();}}

2. Web.xml

ajaxproject selectcityServlet com.denny_blue. Servlet.SelectCityServlet selectcityServlet / servlet / selectcityservlet

3. interface:

ajaxtest.html </ title></p> <p><meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3> <meta http-equiv =" description "content =" this is my page "> </ head> <script type =" text / javascript " > var req = false; function getResult (statevalval) {var URL = "servlet / selectcityServlet? state =" stateval; / ** * In order to send an HTTP request to the server with JavaScript, * You need a class instance to provide You have this feature. * This class was originally proposed as an ActiveX object in IE, called XMLHTTP. * Then, Mozilla, Safari, and some other browsers followed, * An XMLHttpRequest class appears, which supports Microsoft's ActiveX object original method and properties. * / If (window.XMLHttpRequest) {// Mozilla, Safari req = new XMLHttpRequest (); if (req.overrideMimeType) {req.overrideMimeType ( 'text / xml');}} else if (window.ActiveXObject) {/ / Microsoft IE req = new ActiveXObject ( "Microsoft.XMLHTTP"); try {req = new ActiveXObject ( "Msxml2.XMLHTTP");} catch (e) {try {req = new ActiveXObject ( "Microsoft.XMLHTTP");} Catch (e) {}}}} if (! REQ) {Alert ('error, discarding a XMLHTTP instance!'); return false;} / ** * The above statement ensures that our Ajax program is running in the browser * / / ** * After the server responds to your request, what is prepared? * This phase, you only need to tell HTTP Request Object * Which JavaScript function is used to handle this response. * This step is used to set the object onReadyStateChange property to achieve the corresponding JavaScript function name * * Since it has declared what is done after receiving the response, it is now necessary to issue a request. * The Open () and send () method of the HTTP request class is called * Open () method: * The first parameter is the way HTTP request - Get, Post, Head or any other way you want to use, server support .</p> <p>* The name of the way is capitalized, otherwise some browsers (such as firefox) may not process the request. * You can go to W3C SPECS to get more information about the HTTP request method you can use. * The second parameter is the URL of the requested page. * The third parameter is used to set whether the request is asynchronous. * If it is true, the function of JavaScript will continue to execute when the server has not returned a response. * This is the meaning of A in Ajax. * * Send () method: * Parameters can make any data you want to pass to the server, the data should be the query string of the following format: * name = value & annamename = OtherValue & so = on * / if (req) {Req.open ("Get ", URL, TRUE); Req.onReadyStateChange = complete; // Note, there is no parenthek req.send (null) after the function name;}} function completion () {/ ** * When you send a request to the server You also issued a name of the JavaScript function designed to handle the response. * Request.onReadyStateChange = Complete * Let's take a look at this function. * First, it needs to check the status of the request. If the value is 4, * then it means that all server responses have been accepted, and it can continue to handle it. * if (http_request.readystate == 4) {// Everything is ready, the corresponding completed} else {// has not been ready} The list of all values ​​in ReadyState is as follows: * 0 (uninited / uninitialized) * 1 (Load / loading ) * 2 (loaded / loaded) * 3 (Interaction / Interactive) * 4 (Complete / Complete) * * The next step is to check the case code of the HTTP server response. * All possible code is listed on the W3C website. At present, we are only interested in 200 ok. * * After checking the status of the request and the HTTP response, you can decide what to do with the data sent by the server to your data. * You have two ways to access these data: * Request.ResponseText will return the server response as a text string * request.Responsexml will return the response as an XMLDocument object, you can use JavaScript document object model (DOM) Function to handle * * / if (Req.Statystate == 4) {if (req.status == 200) {// We get the XMLDocument object in ResponseXML, and use the DOM method to access the XML document Some of the included contents.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-129355.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="129355" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.048</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'b1VvU7kEwj7RTFfqmyQaIguEaXD2NWl9R1z_2FPwkYWzVMADelhS3swmEYbol3yjetSOXseSnJywpPigkp0mCdmQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>