AJAX-jQuery-JSON

JavaWeb-AJAX

Ajax technology and principle

1.1 Introduction to Ajax

AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).

AJAX is not a new programming language, but a new way to use existing standards.

AJAX is the art of exchanging data with the server and updating part of the web page without reloading the entire page.

1.2 Technology included in Ajax

Everyone knows that ajax is not a new technology, but a combination of several original technologies. It is a combination of the following technologies.

1. Use CSS and XHTML to express.

2. Use the DOM model to interact and display dynamically.

3. Use XMLHttpRequest to communicate asynchronously with the server.

4. Use JavaScript to bind and call

The core of AJAX is the XMLHttpRequest object.

Different browsers have different methods of creating XMLHttpRequest objects.

IE browser uses ActiveXObject, while other browsers use JavaScript built-in object called XMLHttpRequest

1.3 How does Ajax work?

The working principle of Ajax is equivalent to adding an intermediate layer (AJAX engine) between the user and the server to make user operations and server responses asynchronous. Not all user requests are submitted to the server. For example, some data verification and data processing are handed over to the Ajax engine to do it. Only when it is determined that new data needs to be read from the server, the Ajax engine submits the request to the server.

Let’s see the difference from the traditional way

Insert picture description here

Let’s take a look at their respective
interactions
Insert picture description here

Ajax interactive mode of the browser
Insert picture description here

When creating a Web site, performing screen updates on the client side provides users with great flexibility. The following are the functions that can be accomplished using Ajax: Dynamically update the total number of items in the shopping cart, without the user clicking Update and waiting for the server to resend the entire page. Improve site performance, which is achieved by reducing the amount of data downloaded from the server. For example, on Amazon's shopping cart page, when the quantity of an item in the basket is updated, the entire page will be reloaded, which requires downloading 32K of data. If you use Ajax to calculate the new total, the server will only return the new total value, so the required bandwidth is only one percent of the original. Eliminates the page refresh every time the user enters. For example, in Ajax, if the user clicks Next on the paging list, the server data will only refresh the list instead of the entire page. Edit table data directly instead of requiring users to navigate to a new page to edit data. For Ajax, when the user clicks Edit, the static table can be refreshed into a table with editable content. After the user clicks Done, he can send an Ajax request to update the server and refresh the table to include static, read-only data.

Insert picture description here

1.4 Common attributes of XMLHttpRequest

1.onreadystatechange attribute

The onreadystatechange attribute contains a function to process the server response. The following code defines an empty function, which can simultaneously

The onreadystatechange property is set:

xmlHttp.onreadystatechange = function() {
    
     //我们需要在这写一些代码}

2.readyState property

The readyState attribute stores the status information of the server response. Whenever the readyState changes, the onreadystatechange function will be executed.

Possible values ​​of readyState property:

status description
0 The request is not initialized (before calling open())
1 The request has exited (before calling send())
2 The request has been sent (usually from the response to the content header)
3 The request is processing (usually some data is available in the response, but the server has not completed the response)
4 Once the request is completed (you can access the server response and use it)

We want to send an if statement to the onreadystatechange function Tainanjia to test whether our response has been completed (thinking that data can be obtained):

xmlHttp.onreadystatechange = function(){
    
    
	if(xmlHttp.readyState == 4){
    
    
		//从服务器的response获得数据
	}
}

3.responseText attribute

The data returned by the server can be retrieved through the responseText property. In our code, we will set the value of the time text box equal to responseText:

xmlHttp.onreadystatechange = function() {
    
    
    if (xmlHttp.readyState == 4) {
    
    
        document.myForm.time.value = xmlHttp.responseText;
    }
}

Other attributes are as follows:
Insert picture description here

1.5 XMLHttpRequest method

1.open() method

open() has three parameters. The first parameter defines the method used to send the request, the second parameter specifies the URL of the server-side script, and the third parameter specifies that the request should be processed asynchronously.

xmlHttp.open("GET","test.php",true)

2.send() method

The send() method sends the request to the server. If we assume that the HTML file and the PHP file are located in the same directory, then the code is like this:

xmlHttp.send(null);

Other methods are as follows:

Insert picture description here

Two Ajax programming steps

In order to facilitate understanding, I unified a process for AJAX. If you want to implement AJAX, you must follow the next steps:

1. Create an XMLHttpRequest object

2. Set the request method.

3. Call the callback function.

4. Send the request

Let's look at the specific steps:

2.1 Create an XMLHttpRequest object:

The syntax for creating an XMLHttp object is:

var xmlHttp = new XMLHttpRequest();

If it is an IE5 or IE6 browser, the ActiveX object is used , and the creation method is:

var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

Generally, when we write AJAX by hand, we must first determine whether the browser supports the XMLHttpRequest object, if it does, create the object, if it does not, create the ActiveX object. The JS code is as follows:

//第一步:创建XMLHttpRequest对象
var xmlHttp;
if (window.XMLHttpRequest) {
    
    
	//非IE
	xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    
    
	//IE
	xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}

2.2 Set request method

In WEB development, there are two forms of request, one is get and the other is post, so here you need to set which request to use. The open() method of the XMLHttpRequest object is to set the request method. open() method

Features parameter
Specify the request type, URL, and whether to process the request asynchronously Parameter 1: Set the request type (GET or POST), please Baidu about the difference between GET and POST, I won’t explain it here; Parameter 2: The location of the file on the server; Parameter 3: Whether to process the request asynchronously, is true, no Is false.

as follows:

//第二步:设置和服务器端交互的相应参数,向路径http://localhost:8080/JsLearning3/getAjax准备发送数据
var url = "http://localhost:8080/JsLearning3/getAjax";
xmlHttp.open("POST", url, true);

The open method is as follows:

Insert picture description here

GET or POST? Compared with POST, GET is simpler and faster, and can be used in most cases. However, please use POST requests in the following situations:

Cannot use cache files (update files or databases on the server) to send large amounts of data to the server (POST has no data limit) When sending user input containing unknown characters, POST is more stable and reliable than GET

Asynchronous-True or False? AJAX refers to asynchronous JavaScript and XML (Asynchronous JavaScript and XML). If the XMLHttpRequest object is to be used in AJAX, the async parameter of its open() method must be set to true: for web developers, sending asynchronous requests is a huge improvement. Many tasks performed on the server are quite time consuming. Before AJAX, this could cause applications to hang or stop. With AJAX, JavaScript does not need to wait for the server's response, but: Execute other scripts while waiting for the server's response, and process the response when the response is ready

2.3 Call the callback function

If the third parameter of the open method selected in the previous step is true, then the current is an asynchronous request. At this time, you need to write a callback function. The XMLHttpRequest object has an onreadystatechange attribute. This attribute returns an anonymous method, so the callback The function is written here xmlHttp.onreadystatechange=function{}, function{} is the content of the callback function. The so-called callback function is the function implemented by the request after being processed in the background and then returning to the foreground. In this example, the function of our callback function is to receive the data that is fed back to the foreground after background processing, and then display this data on the specified div. Because the data returned from the background may be wrong, the callback function must first determine whether the information returned by the background is correct, and if it is correct, the execution can continue. code show as below:

//第三步:注册回调函数
xmlHttp.onreadystatechange = function() {
    
    
    if (xmlHttp.readyState == 4) {
    
    
        if (xmlHttp.status == 200) {
    
    
        	var obj = document.getElementById(id);
        	obj.innerHTML = xmlHttp.responseText;
        } else {
    
    
        	alert("AJAX服务器返回错误!");
        }
    }
}

In the above code, xmlHttp.readyState is the state where XMLHttpRequest exists. Change from 0 to 4. 0: The request is not initialized. 1: The server connection has been established. 2: The request has been received. 3: The request is being processed. 4: The request has been completed and the response is ready. So here we judge that only when xmlHttp.readyState is 4, can the execution continue.

xmlHttp.status is the result returned by the server, where 200 means correct. 404 means that the page was not found, so here we judge that only when xmlHttp.status is equal to 200, the execution can be continued.

var obj = document.getElementById(id);obj.innerHTML = xmlHttp.responseText;

This code is the core content of the callback function, which is to get the data returned from the background, and then assign this data to the div whose id is testid. The xmlHttp object has two properties that can obtain the data returned from the background, namely: responseText and responseXML, where responseText is used to obtain response data in string form , and responseXML is used to obtain response data in XML form . As for which one to choose depends on the data returned by the backend. In this example, we only display a string of data so we choose responseText. responseXML will be introduced in later examples.

The difference between AJAX status value and status code AJAX status value refers to the steps that will respond to the several states that AJAX has gone through, regardless of whether the access is successful or not, which can be understood as the AJAX running step. Such as: sending, responding, etc., obtained when the AJAX object interacts with the server; use "ajax.readyState" to get. (Consisting of numbers 1~4 unit numbers) AJAX status code refers to the HTTP header information code returned by the server based on the information submitted by the HTTP protocol, regardless of whether the AJAX access is successful or not. The information is obtained using "ajax.status" ; (Composed of three digits 1XX, 2XX, check the RFC in detail) This is why we use the following method to determine whether the information obtained is correct when using AJAX.

if(ajax.readyState == 4 && ajax.status == 200) {
    
    。。。。);}

AJAX operation steps and state value descriptions In the actual operation of AJAX, the access to XMLHttpRequest (XHR) is not completed at one time, but the results obtained after experiencing multiple states. There are 5 kinds of states for this state in AJAX. They are: 0-(uninitialized) the send() method has not been called yet 1-(loading) the send() method has been called, and the request is being sent 2-(loading completed) the send() method has been executed, 3-(interactive ) Parsing the response content 4-(Completed) The response content parsing is complete, and the above state can be called on the client side, where the "0" state is the state value automatically owned after the definition, and for the successful access state (get the information ) Most of us use "4" to judge.

AJAX status code description 1: The request is received, continue processing 2: The operation is successfully received, analyze and accept 3: The request must be processed further 4: The request contains an incorrect syntax or cannot be completed 5: The server failed to execute a fully valid request

The details are as follows:

100-The client must continue to make the request 101-The client requires the server to convert the HTTP protocol version according to the request 200-The transaction is successful 201-The URL of the new file is prompted 202-Accepted and processed, but the processing is not completed 203-Return information Uncertain or incomplete 204-The request was received, but the returned information is empty 205-The server has completed the request, and the user agent must reset the currently browsed file 206-The server has completed part of the user's GET request 300- The requested resource can be obtained in many places 301-Delete the requested data 302-Found the requested data in other addresses 303-Suggest the client to visit other URLs or access methods 304-The client has executed the GET, but the file has not changed 305 ——The requested resource must be obtained from the address specified by the server. 306——The code used in the previous version of HTTP. 307 is no longer used in the current version. 307——Declare that the requested resource is temporarily deleted. 400——Incorrect request, such as syntax error 401 -Request authorization failed 402-Keep valid ChargeTo header response 403-Request not allowed 404-No file, query or URl found 405-The method defined by the user in the Request-Line field is not allowed 406-According to the user sent Accept drag, the requested resource is not accessible 407——Similar to 401, the user must first be authorized on the proxy server 408——The client did not complete the request within the time specified by the user 409——For the current resource status, the request cannot be completed 410—— —This resource is no longer available on the server and there is no further reference address 411 — The server rejects the user-defined Content-Length attribute request 412 — One or more request header fields are wrong in the current request 413 — The requested resource is larger than the server Allowed size 414-the requested resource URL is longer than the length allowed by the server 415-the requested resource does not support the requested item format 416-the request contains the Range request header field, there is no range indication value in the current requested resource range, and the request does not Contains If-Range request header field 417-the server does not meet the expected value specified in the Expect header field of the request. If it is a proxy server, it may be that the next server cannot meet the request. 500-the server generates an internal error501-The server does not support the requested function 502-The server is temporarily unavailable, sometimes to prevent system overload 503-Server overload or suspension of maintenance 504-Gateway overload, the server uses another gateway or service to respond to the user, waiting Longer time setting 505-the server does not support or reject the HTTP version specified in the request header

2.4 Send request

//第四步:设置发送请求的内容和发送报送。然后发送请求
var uname= document.getElementsByName("userName")[0].value;
var upass= document.getElementsByName("userPass")[0].value ;
var params = "userName=" + uname+ "&userPass=" +upass+ "&time=" + Math.random();
// 增加time随机参数,防止读取缓存
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");

// 向请求添加 HTTP 头,POST如果有数据一定加加!!!!
xmlHttp.send(params);

If you need to POST data like an HTML form, use setRequestHeader() to add an HTTP header. Then specify the data you want to send in the send() method.

Three jquery ajax operation

3.1 The shortcomings of traditional Ajax

Cumbersome steps

There are many methods, attributes, and common values ​​that are not easy to remember

3.2 ajax() method

Remote data can be loaded by sending HTTP requests. It is the lowest-level Ajax implementation of jQuery and has high flexibility.

.ajax([settings]);//Parameter settings is the parameter list of the .ajax() method, which is used to configure the key-value pair collection of the Ajax request;

$.ajax({
    
    
    url:请求地址
    type:"get | post | put | delete " 默认是get,
    data:请求参数 {
    
    "id":"123","pwd":"123456"},
    dataType:请求数据类型"html | text | json | xml | script | jsonp ",
    success:function(data,dataTextStatus,jqxhr){
    
     },//请求成功时
    error:function(jqxhr,textStatus,error)//请求失败时
})

3.3 The get() method loads information through a remote HTTP GET request.

This is a simple GET request function to replace the complicated $.ajax

$.get(url,data,function(result) {
//省略将服务器返回的数据显示到页面的代码
});

url: the requested path

data: data sent

success: success function

datatype returned data

Four JSON

4.1, what is JSON

JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy to read and write. At the same time, it is easy to parse and generate by machine. It is based on JavaScript Programming Language, Standard ECMA-262 3rd Edition-a subset of December 1999. JSON uses a text format that is completely language-independent, but also uses habits similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.

4.2, JSON object definition and basic use

In the standard json format, the json object is enclosed in parentheses. The attribute in the object, that is, the key of json, is a string, so it must be enclosed in double quotation marks. Use commas to separate each group of keys.

4.2.1 Definition of JSON

Json definition format:

var 变量名 = {
    
    
“key” : value , 	// Number类型
“key2” : “value” , 	// 字符串类型
“key3” : [] , 	// 数组类型
“key4” : {
    
    }, 	// json 对象类型
“key5” : [{
    
    },{
    
    }] 	// json 数组
};

4.2.2, JSON object access

The json object, as the name suggests, knows that it is an object. The key inside is the attribute of the object. If we want to access the properties of an object, we only need to use the method of [object name. property name].

<script type="text/javascript">
    // json的定义
    var jsons = {
    
    
        "key1":"abc", // 字符串类型
        "key2":1234, // Number
        "key3":[1234,"21341","53"], // 数组
        "key4":{
    
     // json类型
        "key4_1" : 12,
        "key4_2" : "kkk"
        },
        "key5":[{
    
     // json数组
        "key5_1_1" : 12,
        "key5_1_2" : "abc"
    },{
    
    
    	"key5_2_1" : 41,
    	"key5_2_2" : "bbj"
	}]
};

    // 访问json的属性
    alert(jsons.key1); // "abc"
    // 访问json的数组属性
    alert(jsons.key3[1]); // "21341"
    // 访问json的json属性
    alert(jsons.key4.key4_1);//12
    // 访问json的json数组
    alert(jsons.key5[0].key5_1_2);//"abc"
</script>

4.3, the use of JSON in java

We want to use json and java, we need to use a third-party package. It is

Insert picture description here

Conversion between Java objects and json

"1" single object or map collection

java->json:

Users user2=new Users();
user2.setUsername("李四");
user2.setPassword("abc");
user2.setAge(20);
JSONObject obj=JSONObject.fromObject(user);//obj就是json格式的

json->java:

String str="{'username':'李四','password':'admin','age':19}";
JSONObject json=JSONObject.fromObject(str);
Users user=(Users)JSONObject.toBean(json,Users.class);

"2" Object collection and json conversion

java collection->json array:

List list=new ArrayList();
list.add("dd");
list.add("aa");
JSONArray obj=JSONArray.fromObject(list);//set也是这么转

json array -> java collection:

Way 1:

String str2="[{'age':20,'password':'abc','username':'李四'},
{'age':10,'password':'adb','username':'张三'}]";
JSONArray json2=JSONArray.fromObject(str2);
Object[] obj=(Object[])JSONArray.toArray(json2,Users.class);

Way 2:

String str3="[{'age':20,'password':'abc','username':'李四'},
{'age':10,'password':'adb','username':'展示干'}]";

JSONArray json3=JSONArray.fromObject(str3);
//默认转换成ArrayList
List<Users> list=(List<Users>) JSONArray.toCollection(json3,Users.class);

ajax example 2-automatic data filling:

page

':‘张三’}]";
JSONArray json2=JSONArray.fromObject(str2);
Object[] obj=(Object[])JSONArray.toArray(json2,Users.class);


方式2:

String str3="[{'age':20,'password':'abc','username':'李四'},
{'age':10,'password':'adb','username':' Show dry'}]";

JSONArray json3=JSONArray.fromObject(str3);
//默认转换成ArrayList
List list=(List) JSONArray.toCollection(json3,Users.class);


ajax实例2-实现数据的自动填充:

页面

Guess you like

Origin blog.csdn.net/weixin_43515837/article/details/112725792