Ajax - learning notes

Slightly drunk CC 2022-06-23 17:35:06 阅读数:479

ajaxlearningnotes

Reference resources / Excerpts from books :w3cschool、 The Internet
Refer to the picture : From the Internet / Offer yourself
explain : My relevant blog is only for reference !

One 、 brief introduction

AJAX = Asynchronous JavaScript And XML( Asynchronous JavaScript and XML)
Through a small amount of data exchange with the server in the background ,AJAX Asynchronous update of web pages . This means that you can load the entire page without reloading it , Update a part of the web page . To put it simply ,Ajax It's a browser through js Initiate asynchronous request , Local page update technology .

1.1 Workflow

 Insert picture description here

Two 、Ajax Request case

Ajax The application needs to write the client JS Scripts and back-end code .
Ajax The core object of an asynchronous request is XMLHttpRequest object ( abbreviation :XHR), Use XMLHttpRequest(XHR) Objects can interact with the server . You can learn from URL get data , And without having to refresh the entire page . This allows the web page to update the local content of the page without affecting the user's operation .

2.1 obtain Ajax The core object

To cope with all browsers , Include IE5 and IE6, Please check whether the browser supports XMLHttpRequest object . If the support , establish XMLHttpRequest object , If not , Create ActiveX object :

<script>
var xhttp;
if (window.XMLHttpRequest) {

//Chrom、IE7+、Firefox、Safari as well as Opera
xhttp = new XMLHttpRequest();
} else {

//code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
</script>

【 Be careful 】 Modern browsers do not allow cross domain access . So try loading pages and XML All files must be on the same server .

2.2 XMLHttpRequest Object properties

attribute explain
onreadystatechange Define a when readyState attribute Functions called when changes occur
readyState preservation XMLHttpRequest The state of
0: Request not initialized
1: Server connection established
2: Request received
3: Processing request
4: Request completed and response ready
responseText Returns the response data as a string
responseXML With XML Data return response data
status Return the requested status number
200:“ complete ”
400:“ Syntax error in request ”
403:“ Forbidden ( Resource not available )”
404:“ Not found ”
500:“ Server internal error ”
statusText Return status text ( for example :“OK” perhaps “Not Found” etc. )

2.3 XMLHttpRequest Object methods

Method explain
new XMLHttpRequest() Create a new XMLHttpRequest object
abort() Cancel current request
getResponseHeader() Return specific header information
getAllResponseHeaders() Return header information
open(method,url,async,[user],[psw]) Specified request
method: Request type GET or POST
url:“ Request resource path ”
async:true( asynchronous ) or false( Sync )
user:[ Optional ] user name
psw:[ Optional ] password
send() Send request to server , be used for GET request
send(string) Send request to server , be used for POST request
setRequestHeader(header,value) Add... To the header to send label / Key value pair
header: Name of specified header
value: Value of specified head

2.4 GET or POST The choice of

GET Than POST Simpler and faster , Can be used in most cases .

however , Always use... In the following cases POST:

  • Unable to use cache file ( Update files or databases on the server )
  • Send large amount of data to server (POST There is no data size limit )
  • Send user input ( Can contain unknown characters ),POST Than GET More stable and safer

2.5 Registered user name asynchronous verification case

The front desk

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax Register user name demo</title>
</head>
<body>
<script>
// obtain Ajax The core object 【 Use XMLHttpRequest(XHR) Objects can interact with the server 】
function getXHR() {

var xmlhttp; //XMLHttpRequest The object of 
if (window.XMLHttpRequest) {

// IE7+, Firefox, Chrome, Opera, Safari Browser execution code 
xmlhttp = new XMLHttpRequest();
} else {

// IE6, IE5 Browser execution code 
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
// asynchronous GET Requested onclick event 
function asyncGetRequest() {

//【ajax Use steps 】
//1. get ajax The core object 
var xhr = getXHR();
//2. Set wait for server response 【 Process the data returned from the server response 】
xhr.onreadystatechange = function() {

// Judge XMLHttpRequest object xhr The state of 
// Only 【readyState=4: Request completed , And the response is ready 】【status=200: Express "OK"】 The data returned by the server can be obtained 
if (xhr.readyState == 4 && xhr.status == 200) {

// Perform page echo of data returned from the database 
document.getElementById("tipsMsg").innerHTML = xhr.responseText;
}
}
//3. Send a request 
var username = document.getElementById("username").value;
//3.1 open(): Specify the type of request 、URL And whether requests are processed asynchronously .【post and get There's a difference between submission 】
xhr.open("GET", "UserServlet?method=ajaxGet&username=" + username, true);
//3.2 send(): Send the request , When using post Request mode , to send() Incoming request parameters ; When using get When asked ,send() No parameters are required in ;
xhr.send();
}
// asynchronous POST Requested onclick event 
function asyncPostRequest() {

//【ajax Use steps 】
//1. get ajax The core object 
var xhr = getXHR();
//2. Set wait for server response 【 Process the data returned from the server response 】
xhr.onreadystatechange = function() {

// Judge XMLHttpRequest object xhr The state of 
// Only 【readyState=4: Request completed , And the response is ready 】【status=200: Express "OK"】 The data returned by the server can be obtained 
if (xhr.readyState == 4 && xhr.status == 200) {

// Perform page echo of data returned from the database 
document.getElementById("tipsMsg").innerHTML = xhr.responseText;
}
}
//3. Send a request 
var username = document.getElementById("username").value;
xhr.open("POST", "UserServlet", true);
// effect : The function is to simulate a form post request , Encapsulate request parameters into Form Datra Transmission of , stay url Parameter not seen in .
// If you need something like HTML The form is like that. POST data , Please use setRequestHeader() To add HTTP head 
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("method=ajaxPost&username=" + username);
}
</script>
<h2>ajax Registration tips Case study </h2>
// stay span The local submission request in the tag and the corresponding text data of the echo server 
user name :<input type="text" id="username" name="username" /><span id="tipsMsg"></span><br />
password :<input type="password" name="pwd"><br />
<input type="button" onclick="asyncGetRequest()" value=" asynchronous GET Request to verify user name " />
<input type="button" onclick="asyncPostRequest()" value=" asynchronous POST Request to verify user name " />
</body>
</html>

backstage

package com.cb.servlet;
import com.cb.servlet.base.BaseServlet;
/** * Handle ajax The asynchronous GET And asynchronous POST request */
@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends BaseServlet {

//ajax asynchronous GET Processing of requests 
protected String ajaxGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// Obtain form data for verification 【 Simulation judgment 】 whether username Has been registered 
String username = request.getParameter("username");
if (" Xu Chu ".equals(username)){

return "html:<span style=\"color: indianred\"> The user name is already registered , Please try something else !!!</span>";
}
return "html:<span style=\"color: green\"> The user name has not been registered </span>";
}
//ajax asynchronous POST Processing of requests 
protected String ajaxPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// Obtain form data for verification 【 Simulation judgment 】 whether username Has been registered 
String username = request.getParameter("username");
if (" Xu Chu ".equals(username)){

return "html:<span style=\"color: indianred\"> The user name is already registered , Please try something else !!!</span>";
}
return "html:<span style=\"color: green\"> The user name has not been registered </span>";
}
}
package com.cb.servlet.base;
/** * The servlet Inherited HttpServlet * 1. Format code for receiving parameters ; Response data type and encoding format * 2. according to request Parameters passed in the domain (method=xxx) Using the reflection , Determine what method to use to process the request * 3. Determine how to respond according to the return value of the calling method 【 Request forwarding , Redirect , Respond to 】 */
public class BaseServlet extends HttpServlet {

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// The request and response encoding format is already in Filter Set in 
// Receiving parameters method Value , Call a custom method based on its value 
String method = request.getParameter("method");
// because method=value Of value Is the name of the method to be called , According to this point, the reflection call 
Class<? extends BaseServlet> aClass = this.getClass();
// Get the method object to call 
//getDeclaredMethod(String name, Class<?>... parameterTypes) Return to one Method object (Method), It reflects the specified declared methods of the class or interface represented by this 
try {

Method declaredMethod = aClass.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
// about protected and private Decorated methods or attributes should use .setAccessible(true) To cancel the access rights check 
declaredMethod.setAccessible(true);
//invoke(Object obj, Object... args) In the specified object with the specified parameters obj Call this obj Method is the basic method of object representation declaredMethod.
// result The return value of the method called for reflection dynamics 
String result = (String) declaredMethod.invoke(this, request, response);
System.out.println("declaredMethod: "+declaredMethod);
System.out.println(" Return value of method result: "+result);
//【 New optimization part 】
// Determine whether the return value of the method is of the type , To perform different response types 【 Request forwarding , Redirect , Respond to 】
if (!"".equals(result)){

// obtain ":" Index position of , To get : String after [ The index is from 0 Start ]
int index = result.indexOf(":");
// Began to intercept : String after 
String pathOrOther = result.substring(index + 1);
// Judge result Prefix 
if (result.startsWith("forward")){

// Request forwarding 
request.getRequestDispatcher(pathOrOther).forward(request,response);
}else if (result.startsWith("redirect")){

// Redirect 
response.sendRedirect(request.getContextPath() + pathOrOther);
}else{

// With html The first return value is Direct response html And content to the browser 
PrintWriter out = response.getWriter();
out.write(pathOrOther);
}
}
} catch (Exception e) {

e.printStackTrace();
}
}
}

3、 ... and 、jQuery Medium Ajax request 【 recommend 】

Direct use of native js Write ajax The code of asynchronous interaction is cumbersome , It is suggested to use jQuery Packaging method to achieve ajax Asynchronous interaction .

3.1 jQuery ajax Method 【 Not recommended 】

3.1.1 Common properties

grammar :$.ajax({key:value,···})

attribute explain
url Address to send request ; The default value is : Current page address
type Type of request , GET or POST
data Data sent to the server
How to write it 1:key1=value1&key2=value2
How to write it 2:{key1:value1,key2:value2}
dataType The data type of the response , Commonly used :
xml: return XML file , You can use jQuery Handle
html: return Pure text HTML The information contains script The label will insert dom When the
script: Return to plain text JavaScript Code . Results will not be automatically cached . Unless set “cache” Parameters . Be careful : On remote request ( Not in the same domain ), all POST All requests will be converted to GET request .( Because will use DOM Of script Tag to load )
json: return JSON data
text: Returns a plain text string
success The function called when the request is successful
error Function called when the request fails

3.1.2 success() The parameters of the callback method

function(response,status,xhr)

Parameters explain
response Contains the result data from the request
status Include request status (“success”,“notmodified”,“error”,“timeout”,“parsererror”)
xhr contain XMLHttpRequest object , You can use xhr.status Get status code

【 Be careful 】

  1. If the server returns json character string , Client's dataType=json when ,$.ajax() Will automatically json String to json object , We don't need to use JSON.parse() De conversion ;
  2. If the client dataType When the data type is inconsistent with the server-side response , The request fails , Automatically called error Callback function .

3.1.3 Case study

The front desk

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jqueryAjax.html</title>
</head>
<!-- Mode one : Introduce local jQuery library -->
<!-- <script src="/js/jquery.min.js"></script> -->
<!-- Mode two : Introduce online jQuery library -->
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<body>
<h2>jqueryAjax.html【 Use jQuery Packaging method to achieve ajax Asynchronous interaction 】</h2>
Please enter the user name to be registered :<input type="text" id="uname" name="userName" /><span id="tipMsg"></span><br /><br />
<input type="button" value="jQuery ajax() Send asynchronous request " onclick="jqueryAjax()">
</body>
<script>
// grammar : $.ajax({key:value,....})
function jqueryAjax() {

$.ajax({

url: "AjaxTestServlet", // Address to send request 
type: "GET", // Type of request 
data: {

method: "registCheck",
userName: $("#uname").val()
}, // Request parameters ; Format :"key=value" perhaps {key:value}
//【dataType: The data type that the client wants the server to return ; If this type is different from the type actually returned by the server , Will execute error Callback 】
dataType: "html", // The data type of the response 
// Call... When the request succeeds success Callback function ()
success: function(response, status, xhr) {

// Display the returned data in the specified position 
$("#tipMsg").html(response); //html(): Get or set the content inside the element ( Parse tags and CSS style )
//response: Contains the result data from the request 
//status: Contains the status of the request ("success","notmodified","error","timeout","parsererror")
//xhr: contain XMLHttpRequest object , You can use xhr.status Get status code 
console.log("response:" + response); //response:<span style="color:red"> The user name already exists </span>
console.log("status:" + status); //status:success
console.log("xhr:" + xhr); //xhr:[object Object]
console.log("xhr.status:" + xhr.status); //xhr.status:200
},
// If the client dataType When the data type is inconsistent with the server-side response , The request fails , Automatically called error Callback function .
error: function(xhr, textStatus, errorThrown) {

console.log("xhr:" + xhr); //xhr:[object Object]
console.log("textStatus:" + textStatus); //textStatus:error
console.log("errorThrown:" + errorThrown); //errorThrown:
}
})
}
</script>
</html>

backstage

import com.cb.dao.impl.AdminDaoImpl;
import com.cb.servlet.base.BaseServlet;
@WebServlet(name = "AjaxTestServlet", value = "/AjaxTestServlet")
public class AjaxTestServlet extends BaseServlet {

/** * Check the existence of the registered name , Used to prompt the user 【ajax Data interaction 】 * @param request * @param response * @return Return the response data 【 Most of the time return to json Formatted data 】 * @throws ServletException * @throws IOException */
protected String registCheck(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String userName = request.getParameter("userName");
int i = new AdminDaoImpl().adminNameCount(userName);
if (i > 0){

return "html:<span style=\"color:red\"> The user name already exists </span>";
}else {

return "html:<span style=\"color:green\"> User name available </span>";
}
}
}

 Insert picture description here

3.2 jQuery get Method 【 recommend 】

$.get() Methods and $.post() similar , The request it sends is GET request .

3.2.1 grammar

grammar :$.get(url ,[data],[callback],[ type]);
Essential URL Parameter specifies the requested resource path , The other three parameters are optional

Parameters explain
url Specify the requested resource path
data To be sent key=value Parameters
callback Callback function when the request is successful
type Data type returned ,xml、html、json、text

3.2.2 Case study

//$.get(url ,[data],[callback],[ type]);
function jqueryGet() {

$.get("AjaxTestServlet","method=registCheck&userName="+$("#uname").val(),function (data,status){

$('#tipMsg').html(data);
console.log("data:"+data);//data:<span style="color:red"> The user name already exists </span>
console.log("status:"+status);//status:success
},"html")
}

3.3 jQuery post Method 【 recommend 】

$.post() Methods by HTTP POST Request data from the server .

3.3.1 grammar

grammar :$.post(url ,[data],[callback],[ type]);
Essential URL Parameter specifies the requested resource path , The other three parameters are optional

Parameters explain
url Specify the requested resource path
data To be sent key/value Parameters ( Format 1:"key=value"; Format 2:{key:value}
callback Callback function when the request is successful
type Data type returned ,xml、html、json、text

Be careful : If the server returns json character string , Client's type=json when , be $.post() Will automatically json String to json object .

3.3.2 Case study

//$.post(url ,[data],[callback],[type]);
function jqueryPost() {

//url: Address to send request 
//[data]: Request parameters ; Format :"key=value" perhaps {key:value}
//[callback]: Callback function when the request is successful .
//[type]: The default value is text.[ The type of data that the client wants the server to return ]
$.post("AjaxTestServlet",{
method:"registCheck",userName:$("#uname").val()},function (data, status) {

//functin In callback function data: Contains the result data from the request 
//functin In callback function status: Contains the status of the request ("success","notmodified","error","timeout","parsererror")
$("#tipMsg").html(data);// Assign the data response to the page 
console.log("data:"+data);//data:<span style="color:red"> The user name already exists </span>
console.log("status:"+status);//status:success
},"html")
}

3.4 jQuery getJSON Method 【 recommend 】

$.getJSON() This method uses GET Request to get... From the server json data

3.4.1 grammar

grammar :$.getJSON(url ,[data],[callback]);
Essential URL Parameter specifies the requested resource path , Other parameters are optional

Parameters explain
url Specify the requested resource path
data To be sent key=value Parameters
callback Callback function when the request is successful

3.4.2 Case study ( Tianxing website API call )

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> E-sports consulting API</title>
<!-- Mode two : Introduce online jQuery library -->
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h2> E-sports consulting API Data request echo </h2>
<div id="timeList" style="width: 80%;height: 200px;float: left">
<input type="button" value=" Click to get E-sports consulting information " onclick="getNewsList()"><br/>
<div id="times">
<table border="1" width="100%" style="text-align: center;">
<tr>
<th> Number </th>
<th> title </th>
<th> source </th>
<th> Creation time </th>
</tr>
</table>
</div>
</div>
<script>
//$.getJSON(url,[data],[callback])
// Call the API
// E-sports consultation list 
function getNewsList() {

$.getJSON("http://api.tianapi.com/esports/index", {
key : " Fill in the secret key you applied for key value ", num : 10},function (data,status,xhr) {

console.log(data.length);
// Go to div Insert table 
for (var i in data.newslist) {

var sig = data.newslist[i];
var $sigStr = $('<tr><td>'+sig.id+'</td><td>'+sig.title+'</td><td>'+sig.source+'</td><td>'+sig.ctime+'</td></tr>');
$('#times table').append($sigStr);
}
})
}
</script>
</body>
</html>

 Insert picture description here

版权声明:本文为[Slightly drunk CC]所创,转载请带上原文链接,感谢。 https://qdmana.com/2022/174/202206231443287027.html