10. 1 what is ajax?
The full name of ajax is Asynchronous JavaScript and XML. It is not a new technology, but an integration of several existing technologies such as JavaScript, XML and CSS
10. Ajax core - XMLHttpRequest
The XMLHttpRequest object is the core of Ajax technology and is used to interact with the server. It can asynchronously send requests and obtain data to the URL of the server without refreshing the current page, so as to achieve the effect of local update in the current page
Syntax:
Based on IE7 or above
xmlHttpRequest =new XMLHttpRequest();
Common methods of XMLHttpRequest object
Method name | explain |
---|---|
open(String method,String url, boolean | Initialize a new HTTP request. Method parameter: Specifies the HTTP request method, such as POST and GET. It is not case sensitive. URL parameter: Specifies the URL of the request. async parameter: optional. Specify whether the request is an asynchronous method. The default is true.user parameter: optional. If the server needs authentication, the user name needs to be specified here; Otherwise, the validation window opens. Password parameter: optional. The password in the authentication information. If the user name is empty, this value will be ignored |
send(String data) | Send request to server data parameter: string type, which sets the data sent through the request body. This parameter setting is affected by the method parameter in the open() method. If the method value is "POST", you can specify this parameter; If the method value is "GET", the parameter is null |
abort() | Cancel current request |
setRequestHeader(String header,String value) | Set the HTTP header information of the request. Header parameter: the name of the HTTP header to be specified. Value parameter: the value corresponding to the specified HTTP header name |
getResponseHeader(String head | Gets the specified HTTP header information from the response. Header parameter: Specifies the name of the HTTP header to get |
getAllResponseHeaders() | Get all HTTP header information of the response |
Get all HTTP header information of the response
Attribute name | explain |
---|---|
onreadystatechange | Set the callback function as the event handler when the readyState property value changes |
readyState | Returns the current status of the request. The value varies from 0 to 4. 0 - not initialized. 1 - initialized. 2 - request sending completed. 3 -- start reading response. 4 -- end of read response |
status | Returns the HTTP status code of the current request. Examples of common values: 200 -- correct return. 404 -- access object not found |
statusText | 404 -- the access object cannot be found, and the response line status of the current request is returned |
responseText | Get the response value as text |
responseXML | Get the response value in XML and parse it into a DOM object to return |
Example:
var id = document.getElementById("name").value; //Step 1: create the Ajax core object var xr = new XMLHttpRequest(); //Step 2: set the callBack function and remember callBack xr.onreadystatechange = callBack; //Step 3: create a request xr.open("get", "Do_Uname?uname=" + id, true) //Step 4: send request xr.send(null); //Step 5: declare callback function function callBack() { //Solve the problem of four pop ups. xr.readyState == 4 means the fourth request, and status==200 means the correct request if (xr.readyState == 4&&xr.status==200) { if (xr.responseText.trim()=="true"){ document.getElementById("span").innerHTML="The user is already registered"; }else { document.getElementById("span").innerHTML="The user is not registered"; } } }
10. 3 use Jquery to simplify the implementation of Ajax
Jquery implements ajax through the $. ajax() method,
The $. ajax() method is the lowest level of ajax implementation
Syntax format:****
$.ajax({settings});settings yes $.ajax()Method is a set of parameters for configuration ajax Collection of requested key value pairs.
Common configuration parameters of $. ajax() method
parameter | type | explain |
---|---|---|
url | String | The requested URL, which defaults to the current page address |
type | String | The request method (POST or GET, the default is GET). JQuery versions after 1.9.0 can use method instead of type |
data | PlainObject or String or Array | Data sent to the server |
dataType | String | The expected data types returned by the server. The available types are XML, HTML, Script, JSON, JSONP and Text |
beforeSend | Function(jqXHR jqxhr, PlainObject settings) | The function invoked before sending a request can be used to set the request level. false will terminate the request. jqXHR parameter: optional. jqXHR is the superset of XMLHttpRequest. Settings parameter: optional, the settings object of the current ajaxO method. |
success | Function (any type result, string textstatus, jqxhr, jqxhr) | The function called when the request is successfully processed. result parameter: optional, the data returned by the server. textStatus parameter: optional, a string describing the status of the request. jqxhr parameter: optional |
error | Function(jqXHR jqxhr, String textStatus, | The function called when the request fails. jqxhr parameters: optional. textStatus parameter: optional, error message. errorThrown parameter: optional, text description of HTTP status |
complete | Function(jqXHR jqxhr, String textStatus) | The function called (whether successful or failed) is invoked after the request is completed. jqxhr parameter: optional. jqxhr parameter: optional. |
timeout | Number | Set request timeout |
global | Boolean | Set whether to trigger global Ajax events. The default value is true |
Example:
$.ajax({ "url": "../Do_SelectBannana", "dataType": "json", "type": "post" , "data": "index=" + num, "success": function (data) { if (data != null) { $("#btr").empty(); for (var i in data) { var node = "<tr>"; node += "<td>" + data[i].bid + "</td>"; node += "<td>" + data[i].bname + "</td>"; node += "<td>" + data[i].bprice + "</td>"; node += "<td>" + data[i].bcolor + "</td>"; node += "<td>" + data[i].btime + "</td>"; node += "</tr>"; $("#btr").append($(node)); } } }, "error": function (data) { alert("report errors") } })
$.get
$.get()Method use GET The syntax structure of asynchronous request is:
Explain the parameters of this function:
url: string type, the address of the ajax request.
Data: optional parameter, object type. The key/value data sent to the server will be attached to the request URL as QueryString.
callback: optional parameter, function type. This function will be called automatically when ajax returns success.
Example:
$.get('Do_Select', '', function (data) { sum = data; x(9999); }, "json") }
$.post()
The $. post() method uses POST to make asynchronous requests. Its syntax structure is:
$.post(url,[data],[callback],[type])
The usage of this method is similar to that of. g e t(), except that there is one more t y p e parameter, so only the T Y P E parameter is introduced here. For other references, the usage of. get() is similar, but there is one more type parameter, so only the type parameter is introduced here, and other references are. get() The usage is almost the same, except that there is one more type parameter, so only the type parameter is introduced here. For other references, please refer to. get() above.
Type: type is the requested data type, which can be html,xml,json and other types. If we set this parameter to json, the returned format is json format. If it is not set, it is the same as the format returned by $. get(), which is a string.
Example:
$.post(url,[data],[callback],[type])
$.getJSON()
$. getJSON() is specially set for ajax to obtain json data, and supports "cross domain" calls. Its syntax format is:
getJSON(url,[data],[callback])
url: string type, sending request address
Data: optional parameter. The Key/value parameter to be sent is the same as the data of get and post types
Callback: optional parameter. Callback function upon successful loading. The same as callback of get and post types
JSON is an ideal data transmission format, which can be well integrated with JavaScript or other host languages, and can be directly used by JS. Compared with the traditional direct sending of "naked" data through GET and POST, JSON is more reasonable and safer in structure. As for the getJSON() function of jQuery, it only sets the ajax() of JSON parameters A simplified version of the function. This function can also be used across domains, which has certain advantages over get() and post(). In addition, this function can let the program execute the callback function X by writing the request url in the format of "myurl?callback=X".
Tip: the data is finally sent through the get method after the url, which determines that the amount of data sent cannot be too much, otherwise the url is too long and the reception fails (the getJSON method cannot be submitted by post).
Example:
if (isbn != "") { $.getJSON("../Do_UpdateBook?opr=abstract", { "isbn": $("#isbn").val(), "abstract": $("#abstract").val() }, function (data) { if (data > 0) { alert("Attach successful!") } else { alert("Attach failed!") } }); } else { alert("Please add the basic information of the book first!"); }
$("div"). load('address') will return a value to div or any tag when it jumps back
10. 4. Data in JSON format
What is JSON?
The full name of JSON is Javascript Object Notation, which is a lightweight data exchange format. It is based on a subset of javascript and adopts a completely language independent text format. In short, JSON is an object representation method that can store and transfer information in the form of text
Syntax:
var JSON object={name:value,name:value,....}
Example:
int max=3; resp.setContentType("text/html;charset=utf-8");//Solve the problem of garbled code if (req.getParameter("index")!=null&&req.getParameter("index")!=""){//Verify that index is empty int index=Integer.parseInt(req.getParameter("index"));//Receive index PrintWriter out = resp.getWriter(); //Convert to an output type BannanaServiceImpl b = new BannanaServiceImpl(); String jos = JSON.toJSONString(b.Do_Selebannana(index,max));//The list collection returned by the receive method //If the java result needs to return the object, it must be converted to json format and then returned by out.print //Because they are two languages, java objects and js objects do not communicate with each other and do not know each other out.println(jos);//Go back out $.ajax({ "url": "../Do_SelectBannana", "dataType": "json", "type": "post" , "data": "index=" + num, "success": function (data) { if (data != null) { $("#btr").empty(); for (var i in data) { var node = "<tr>"; node += "<td>" + data[i].bid + "</td>"; node += "<td>" + data[i].bname + "</td>"; node += "<td>" + data[i].bprice + "</td>"; node += "<td>" + data[i].bcolor + "</td>"; node += "<td>" + data[i].btime + "</td>"; node += "</tr>"; $("#btr").append($(node)); } } }, "error": function (data) { alert("report errors") } })