[Reserved] a summary of some of Ajax and JSON

[Reserved] a summary of some of Ajax and JSON

Author: JK_Rush] [http://www.cnblogs.com/rush/

Big morning to see a good article, because it is concerned about a recent study, the interception of a part I can understand that and added some of their own content, very suitable for beginners to look at.

I. Summary

Ajax] [ASynchronous JavaScript And XML technology is the core XMLHttpRequest object (XHR for short), you can get to the data server by using the XHR object, and then through the DOM to insert data into the page rendering. Although the name is included in XML, but Ajax communication regardless of the data format, so our data format can be XML or JSON [JavaScript Object Notation] and other formats.

XMLHttpRequest object to exchange data with the server in the background, the specific effects include:

  • Update page without reloading the page
  • Request data from the server after the page has loaded
  • Receive data from the server after the page has loaded
  • Send data to the server in the background

  • https://www.cnblogs.com/rush/archive/2012/05/15/2502264.html#lb4)

Second, the text

XMLHttpRequest is a JavaScript object that was designed by Microsoft, and is Mozilla, Apple and Google to adopt, W3C is standardized it. It provides an easy way to retrieve data URL.

We want to create an XMLHttpRequest instance, just a new on OK:

//// Creates a XMLHttpRequest object.
var req = new XMLHttpRequest();

Some people might say: "This can not ah IE6 does not support the original XHR object!" Indeed it is, we will introduce support for older versions of IE6 or method to create a XHR object later.

1, XMLHttpRequest usage

After you create the XHR object, then we have to call an initialization method open (), which accepts five parameters defined as follows:

void open(
   DOMString method, //"GET", "POST", "PUT", "DELETE"
   DOMString url,
   optional boolean async,
   optional DOMString user,
   optional DOMString password
);

By the above definition we know that signature open () method contains five parameters, including parameters method url address is required and, assuming we respect URL: myxhrtest.aspx send a GET request to obtain data, defined as follows:

var req = new XMLHttpRequest();

req.open(
    "GET",
    "myxhrtest.aspx",
    false
);

The code starts by a GET request for myxhrtest.aspx, here are two things to note: First, with respect to the implementation of the code of the URL of the current page (using an absolute path); the second is to call open () method does not actually send the request but only a start request is ready to send.

Can only be sent to the URL using the same port and protocol of the same domain in the request; if the URL of the page and start the requested there is any difference, it will lead to a security error.

To send the request to use the real send () method, send () method takes one parameter, i.e. the data subject to request as sent, if no data is transmitted through the request body, we have to pass a null value. After the call to Send (), the request is dispatched to the server, a complete Ajax request code as follows:

var req = new XMLHttpRequest();

req.open(
    "GET",
    "myxhrtest.aspx",
    false
);
req.send(null);

After sending the request, we need to check whether the request is executed successfully, the status attribute by first determining, in general, HTTP status code 200 may be a success flag. At this time, the response body content is saved to the responseText. Further, the status code 304 indicating a request for the resource has not been modified, may be used directly browser cache data, Ajax synchronization request code is as follows:

if (req != null) {
    req.onreadystatechange = function() {

        if ((req.status >= 200 && req.status < 300) || req.status == 304) {
            //// Do something.
        }
        else {
            alert("Request was unsuccessful: " + req.status);
        }
    };
    req.open("GET", "www.myxhrtest.aspx", true);
    req.send(null);
}

We define a synchronization request in front of Ajax, if we send an asynchronous request, the javascript code execution continues during a request, then the state readyState property determination by request, when readyState = 4, the response data indicates receipt of all, attribute value is defined as follows:

readyState值 description
0 Uninitialized; open has not been called () method
1 Start; send not been called () method
2 Sent; but not yet received a response
3 Receiving; partial response has been received
4 Completed; receive all the response data

Table 1 readyState attribute value

Synchronous request: The request occurs, wait for the server to be finished before continuing the implementation of the current code.

Asynchronous request: The request occurs, without waiting for the server is finished, you can continue with the current code.

Now we want to increase readyState attribute value determination, when readyState = 4, represents all the data has been received, the Ajax asynchronous request code as follows:

if (req != null) {
    req.onreadystatechange = function() {

        //// Checks the asyn request completed or not.
        if (req.readyState == 4) {
            if ((req.status >= 200 && req.status < 300) || req.status == 304) {
                //// Do something.
            }
            else {
                alert("Request was unsuccessful: " + req.status);
            }
        }
    };
    req.open("GET", "www.myxhrtest.aspx", true);
    req.send(null);
}

2, Ajax homologous request

Now that we have achieved a basic understanding of Ajax request, then we will explain the Ajax request through concrete examples of applications and limitations .

In daily life network, we enter the address in the browser's URL to be accessed and press Enter, the browser sends a request to the server, when the server receives the request, the page corresponding request is sent back to the browser, we will find most of the page is loaded, and some have not yet loaded. Generally speaking, the use of asynchronous loading will not affect the already loaded page views, we can achieve asynchronous loading via Ajax.

Here we AdventureWorks database as an example, the product data sheet (Product) is presented to the user through the report, we can implement the reporting requirements through a variety of methods, here we will achieve this function by Ajax.

First of all, we need to back-end data into JSON format, then we define database access object (DAO) Product table, specific codes are as follows:

/// <summary>
/// The product datatable dao.
/// </summary>
public class ProductDao
{
    /// <summary>
    /// Initializes a new instance of the <see cref="ProductDao"/> class.
    /// </summary>
    public ProductDao()
    {
    }

    /// <summary>
    /// Gets or sets the product id.
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// Gets or sets the product name.
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Gets or sets the product serial number.
    /// </summary>
    public string SerialNumber { get; set; }

    /// <summary>
    /// Gets or sets the product qty.
    /// </summary>
    public short Qty { get; set; }
}

Earlier we defined database access object --ProductDao Product table, which contains four properties are the Id, name, serial number and the number of sales.

Next, let's implement database operations Product table.

/// <summary>
/// Product table data access manager.
/// </summary>
public class ProductManager
{
    /// <summary>
    /// The query sql.
    /// </summary>
    private const string Query = 
        "SELECT ProductID, Name, ProductNumber, SafetyStockLevel FROM Production.Product";

    /// <summary>
    /// Stores the object of <see cref="ProductDao"/> into list.
    /// </summary>
    private IList<ProductDao> _products = new List<ProductDao>();

    /// <summary>
    /// Gets all products in product table.
    /// </summary>
    /// <returns>
    /// The list of <see cref="ProductDao"/> object.
    /// </returns>
    public IList<ProductDao> GetAllProducts()
    {
        using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLCONN"].ToString()))
        using (var com = new SqlCommand(Query, con))
        {
            con.Open();
            using (var reader = com.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    var product = new ProductDao
                        {
                            Id = (int)reader["ProductID"],
                            Name = (string)reader["Name"],
                            SerialNumber = (string)reader["ProductNumber"],
                            Qty = (short)reader["SafetyStockLevel"]
                        };
                    _products.Add(product);
                }
            }
        }

        return _products;
    }
}

Earlier we realized database operations --ProductManager Product table, which contains two private fields and Quey _products, there is a data acquisition method of the Product table --GetAllProducts ().

By implementing ProductDao and ProductManager, and we offer GetAllProducts () method to get the data in the Product table, then we have to call this method to get the data.

To make the data passed to the page via JSON format, where we want to create a generic handler (ASHX file),

General handler is ideal for:

  • Create a dynamic picture
  • REST-style return XML or JSON data
  • Custom HTML

Ajax1

1 General processing procedure of FIG.

When you add the general processing program file to the project, it will add a file extension .ashx, now we create a general handler ProductInfo, specific code as follows:

<%@ WebHandler Language="C#" Class="ProductInfo" %>

using System.Runtime.Serialization.Json;
using System.Web;

using ASP.App_Code;

/// <summary>
/// The product data handler.
/// </summary>
public class ProductInfo : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "application/json";

        // Creates a <see cref="ProductManager"/> oject.
        var manager = new ProductManager();

        // Invokes the GetAllProducts method.
        var products = manager.GetAllProducts();

        // Serializes data to json format.
        var json = new DataContractJsonSerializer(products.GetType());
        json.WriteObject(context.Response.OutputStream, products);
    }

    // Whether can resuable by other handler or not.
    public bool IsReusable {
        get {
            return false;
        }
    }
}

It was noted ProductInfo IHttpHandler class implements the interface, which contains a method ProcessRequest () method and a property IsReusable. The ProcessRequest () method for processing inbound Http request. By default, the ProductInfo class will read the content type application / json, then we write the input data stream by JSON format; attribute indicates whether the IsReusable same procedure may be used for processing a plurality of requests, where we set to false If in order to improve performance can also be set to true.

As shown below, we have successfully acquired response data stream by ProductInfo class diagram, and displayed in JSON format.

ajax2

FIG 2 Http Request

When we ask the ProductInfo, it first calls the ProcessRequest () method, and then call GetAllProducts () method to get the data from the database and writes data response stream by JSON format.

Now, we have successfully written the data to which the response stream by JSON format, then we will request data by Ajax manner and the display data to the page.

First, we define the method createXHR () is used to create XMLHttpRequest object, as we mentioned IE6, or older versions do not support XMLHttpRequest () method to create XMLHttpRequest object, so we want to createXHR () method, increased to determine the current browser whether IE6 or older version, if it is, it must achieve through a MSXML ActiveX object library. Accordingly, three different versions may encounter XHR object (MSXML2.XMLHttp6.0, MSXML2.XMLHttp3.0 and Msxml2.XMLHTTP) in IE.

// Creates a XMLHttpRequest object bases on web broswer.
function createXHR() {

    // Checks whether support XMLHttpRequest or not.
    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    }

    // IE6 and elder version.
    else if (typeof ActiveXObject != "undefined") {
        if (typeof arguments.callee.activeXString != "string") {
            var versions = [
        "MSXML2.XMLHttp6.0",
        "MSXML2.XMLHttp3.0",
        "MSXML2.XMLHttp"];

            for (var i = 0; i < versions.length; i++) {
                try {
                    var xhr = new ActiveXObject(versions[i]);
                    arguments.callee.activeXString = versions[i];
                    return xhr;
                }
                catch (ex) {
                    throw new Error(ex.toString());
                }
            }
            return new ActiveXObject(arguments.callee.activeXString);
        }
        else {
            throw new Error("No XHR object available");
        }

    }
    return null;
}

$(document).ready(function() {
    GetDataFromServer();
});
function GetDataFromServer() {

    // Creates a XMLHttpRequest object.
    var req = new createXHR();
      
    if (req != null) {
        req.onreadystatechange = function() {
            if (req.readyState == 4) {
                if ((req.status >= 200 && req.status < 300) || req.status == 304) {
                    ////alert(req.responseText);
                    var jsonTextDiv = document.getElementById("jsonText");

                    // Deserializes JavaScript Object Notation (JSON) text to produce a JavaScript value.
                    var data = JSON.parse(req.responseText);
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        var div = document.createElement("div");
                        div.setAttribute("class", "dataItem");
                        // Inserts data into the html.
                        div.innerHTML = item.Name + " sold " + item.Qty + "; Product number: " + item.SerialNumber;
                        jsonTextDiv.appendChild(div);
                    }
                }
                else {
                    alert("Request was unsuccessful: " + req.status);
                }
            }
        };
        
        // Sends a asyn request. 
        req.open("GET", "ProductInfo.ashx", true);
        req.send(null);
    }
}

Due to the foregoing method we introduced Ajax request occurs, it will not be repeated to introduce, but we note GetDataFromServer () method, the data acquired responseText (JSON format), then parse () method to convert Javascript object JSON format data Finally, the data is inserted into the div, the page rendering is as follows:

ajax3

FIG request result 3 Ajax

Now, we successfully export the data to a page, Perhaps users will find user experience is not good, then we give in relation to the increase page CSS styles.

Due to time, we have the CSS styles defined, as follows:

#header {
    width: 100%;
    margin-left: 10px;
    margin-right: 10px;
    background-color:#480082;
    color: #FFFFFF;
}
body {
    margin-left: 40px;
    margin-right: 40px;
}
div#jsonText {
    background-color: #d9d9d9;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    margin: 10px 0px 0px 0px;
    padding: 0px;
    border: 1px solid #d9d9d9;
}
div.dataItem {
    font-family: Verdana, Helvetica, sans-serif;
    color: #434343;
    padding: 10px;
}
div.dataItem:nth-child(2n) {
    background-color: #fafafa;
}
div.dataItem:first-child {
    -webkit-border-top-left-radius: 6px;
    -webkit-border-top-right-radius: 6px;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
}
div.dataItem:last-child {
    -webkit-border-bottom-left-radius: 6px;
    -webkit-border-bottom-right-radius: 6px;
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
}

We refresh the page, OK now much better results page.

ajax4

FIG 4 Ajax request result

Third, the case

How should I say, this article though heat is good, but there are some ages, and here an example of a modern feel.

Case: Registration page - check username exists

The server response data, when the client uses, to the data as json format. There are two solutions:

  1. $ .Get (type): The last parameter type is specified as "json"
  2. MIME type is provided on the server side
    response.setContentType ( "application / json; charset = utf-8");

First, there must be a registration page regist.html it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册页面</title>
    <script src="../BootStrap/js/jquery-3.2.1.min.js"></script>


    <script>
        //在页面加载完成后
        $(function () {
           //给username绑定blur事件
           $("#username").blur(function () {
               //获取username文本输入框的值
               var username = $(this).val();
               //发送ajax请求
               //期望服务器响应回的数据格式:{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"}
               //                         {"userExsit":false,"msg":"用户名可用"}
               $.get("findUserServlet",{username:username},function (data) {
                   //判断userExsit键的值是否是true

                   // alert(data);
                   var span = $("#s_username");
                   if(data.userExsit){
                       //用户名存在
                       span.css("color","red");
                       span.html(data.msg);
                   }else{
                       //用户名不存在
                       span.css("color","green");
                       span.html(data.msg);
                   }
               });

           }); 
        });

    </script>
</head>
<body>


    <form>

        <input type="text" id="username" name="username" placeholder="请输入用户名">
        <span id="s_username"></span>
        <br>
        <input type="password" name="password" placeholder="请输入密码"><br>
        <input type="submit" value="注册"><br>

    </form>

</body>
</html>

Second, look for the user if there is FindUserServlet.java

package wzm.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取用户名
        String username = request.getParameter("username");

        //2.调用service层判断用户名是否存在

        //期望服务器响应回的数据格式:{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"}
        //                         {"userExsit":false,"msg":"用户名可用"}

        //设置响应的数据格式为json
        response.setContentType("application/json;charset=utf-8");
        Map<String,Object> map = new HashMap<String,Object>();

        if("tom".equals(username)){
            //存在
            map.put("userExsit",true);
            map.put("msg","此用户名太受欢迎,请更换一个");
        }else{
            //不存在
            map.put("userExsit",false);
            map.put("msg","用户名可用");
        }

        //将map转为json,并且传递给客户端
        //将map转为json
        ObjectMapper mapper = new ObjectMapper();
        //并且传递给客户端
        mapper.writeValue(response.getWriter(),map);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

Guess you like

Origin www.cnblogs.com/wangzheming35/p/11925748.html