What is AJAX (Asynchronous javascript and XML)

It’s a technique used to improve the user experience by making asynchronous requests to the server using special objects built into the browser (XMLHttpRequest, or Ajax objects), and the server returns some data (usually not the entire page) that the browser uses to update part of the page. There is no surface refresh during the whole process of accessing the server, which will not interrupt the user’s operation

Asynchronous request: when a request is sent, it does not destroy the current page. The user can still do other operations on the current page

How do I get ajax objects

Compatibility issues:

  • Ie uses ActiveXObject

  • Other browsers are XMLHttpRequest. There are compatibility issues here, and there are different solutions for different browsers. The underlying solution is:

    function getxhr() { var xhr = null; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject(“Microsoft.XMLHttp”); } return xhr; }

Properties of ajax objects

  • OnReadyStateChange is used to bind an event handler that handles readyStateChange events that are generated when the readyState property in an Ajax object changes from 0 to 1
  • ReadyState has five values (0,1,2,3,4) that indicate the state of communication between the ajax object and the server. A value of 4 indicates that the ajax object has retrieved all the data returned by the server. The event handler can read the data from the object
  • ResponseText Text data in the object returned
  • XML data in the object returned by responseXML
  • Status Obtain the status code 500 Server error 200 Server Normal 404 Request path cannot be found 302 Redirection

The programming steps

Getting ajax objects

For example, var XHR = getXhr();

In the request

  • Send a GET request

  1. xhr.open(“get”,”check_uname.do? uname=tom&age=18″, true); The first parameter is the request mode, the second parameter is the address of the request, and the third parameter is whether to send an asynchronous request, which is usually true. If it is false, when the request is sent, the page does not disappear, but the browser locks the current page, and the user cannot do any other operations on the current page

  2. xhr.onreadystatechange=function1; Bind an event that will be called when the state transitions

  3. xhr.send(null);


  • Send a POST request

xhr.open("post", "get_luckyNum.do", true);
Copy the code

The three parameters are almost the same as get, but instead of adding a parameter to the request address, it will be loaded in the last send

xhr.send("name=mackyhuang");
Copy the code

That’s the first difference and then you need to add a request header (HTTP, if you’re sending a POST request, you should have a connten-type request header in the request packet). By default, Ajax doesn’t have a request header, so it does

xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
Copy the code

Write server-side programs

Usually you don’t need to return the full page, only partial data

Write once function1 ();

That’s the event handler

Function function1() {if(xhr.readyState == 4&&xhr.status == 200) {var TXT = xhr.responseText(); Use TXT file to modify the page content}}Copy the code

The whole basic code

Set the response function

<input id="username" type="text" name="username" onblur="check_name();" >Copy the code
Get request function specific code
    function check_name() {
        var username = document.getElementById("username").value;
        var msg = document.getElementById("msg");
        var xhr = getxhr();
        xhr.open("get"."check_login.do? username=" + username, true);
        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4 && xhr.status == 200)
            {
                vartxt = xhr.responseText; msg.innerHTML = txt; }}; xhr.send(null);
    }
Copy the code

#### Post request function specific code

function get_num() { var pLable = document.getElementById("lucky"); var xhr = getxhr(); xhr.open("post", "get_luckyNum.do", true); xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200) { var txt = xhr.responseText; pLable.innerHTML = txt; }}; xhr.send("name=mackyhuang"); }Copy the code

The cache problem

When you use Internet Explorer to send a GET request to Ajax, there is a cache problem, that is, only the first click is valid, and each subsequent click is not responded, because Internet Explorer determines whether the request address has been visited, and if so, it will call the result of the last visit to display. The solution is to add? The random number

Coding problem

Get submission mode, AJAX code of IE GBK, other browser code is UTF-8, on the server side code is ISO-8859-1

  • Set URLEncoding= UTF-8 in the configuration file
  • Then use javascript’s built-in function EncodeURL to encode it to UTF-8, which all browsers use at this point

Post submission, utF-8 for all browsers, ISO-8859-1 on the server

  • request.setCharacterEncoding(“utf-8”);

what is Json

It’s a lightweight data interchange format that is lightweight compared to XML, faster parsing, smaller documents

grammar

  • {“”:””,””:””} double quotation marks are required
  • The value can be stirng Number NULL Object true/false
  • If the attribute value is string, double quotes are required

Convert the object to JSON at the server

  • You need a package json-lib

      JSONObject jsonObject = JSONObject.fromObject(people);
      return jsonObject.toString();
      JSONArray jsonObject = JSONArray.fromObject(arrayList);
      return jsonObject.toString();
    Copy the code

The JSONObject and JSONArray classes in the package need to generate a single JSON and a JSON array, respectively

The browser converts JSON to objects

  • Javascripe’s built-in object JSON needs one of its methods, parse():

      var object = JSON.parse(jsonString);
    Copy the code

JQuery support for Ajax

$.ajax({})

{} is an object whose properties:

  • Url Request address
  • Data request parameters
  • Type Request type
  • DataType The type of the value returned
  • The SUCCESS server returns a successful event handler
  • The error server returns an event handler for the exception

Write an Ajax that returns eight pieces of data to the page every five seconds

Presentation layer code:

	<script type="text/javascript">
	
		$(function(){
			setInterval(do_query, 5000);
		});
		
		function do_query()
		{
			$("#tb1").empty();
			$.ajax({
				"url":"query.do",
				"type":"post",
				"dataType":"json",
				"success":function(books){
					$("#tb1").empty();
					//alert(books);
					for(var i = 0; i < books.length; i++)
					{
						var book = books[i];
						$("#tb1").append("<tr><td>" + book.name + "</td><td>" 
								+ book.price + "</td><td>" + 
								book.page + "</td></tr>");
					}
				}
			})
		}
	</script>
Copy the code

Server code

    response.setContentType("text/html; charset=utf-8");
    request.setCharacterEncoding("utf-8");
    String path = request.getRequestURI();
    String action = path.substring(path.lastIndexOf("/"), path.lastIndexOf("."));
    System.out.println(action);
    PrintWriter printWriter = response.getWriter();
    if("/query".equals(action))
    {
        ArrayList<Book> books = new ArrayList<Book>();
        Random random = new Random();
        for(int i = 0; i < 8; i++)
        {
            books.add(new Book("Java Enterprise Application Development" + random.nextInt(8888), 
                    88.189 + random.nextInt(8888)));
        }
        JSONArray jsonArray = JSONArray.fromObject(books);
        String json = jsonArray.toString();
        System.out.println(json);
        printWriter.print(json);
    }
Copy the code

load

This is a lightweight Ajax request function used when you need to add the returned parameters directly to a label

Write the code on the server side, and then in the JSP

$("#lucky").load("get_luckyNum.do");
Copy the code

Blog post is the author originally in another platform, now migrated