Ajax study notes in jquery 1_jquery
A brief introduction to AJAX:
AJAX refers to Asynchronous JavaScript And XML (Asynchronous JavaScript And XML), a web development technology for creating interactive web applications. AJAX allows JavaScript to communicate directly with the server using JavaScript's XMLHttpRequest object. This object allows your JavaScript to exchange data with the web server without reloading the page.
jQuery is a javascript framework, a lightweight encapsulation of javascript that is easy to understand.
Ajax is an asynchronous request technology combined with xml javascript. It can achieve dynamic refresh.
ajax preparation:
1.jquery download:
The latest download address of the official website: http://blog.jquery.com/2011/09/01/jquery-1- 6-3-released/
When downloading, select jQuery 1.6.3 Minified or jQuery 1.6.3 Uncompressed, right-click and select "Download using Thunder"
2. Main knowledge introduction
2.1. Ajax asynchronous transmission steps :
1. Use dom to get the value of the attribute in the text box
document.getElementById("id name").value
2. Create an XMLHttpRequest object
Depending on the browser, there are XMLHttpRequest, ActiveXObject two kinds of objects
3. Register callback function When registering the callback function, only the function name is required, do not add brackets
When registering the callback function, the data returned by the server will be obtained:
The first way: Get the server Plain text data output from the client
The second way: use responseXML to accept the DOM object of the XML data object
4. Set the connection information
5. Send the data and start interacting with the server
Post method/get method
2.2.ajax main method:
(1).getElementById("id attribute value"):
Get the object according to the specified id attribute value
(2 ).getElementsByTagName(tagname):
By searching for any HTML element in the entire HTML document, return a collection of elements with the specified name
(3). Selector:
The selector includes basic selector and hierarchical selection selector, attribute selector, etc. This program only has the basic selector #id, such as:
$("#myDiv"): Find the element with the ID "myDiv"
2.3.XMLHttpRequest object:
XMLHttpRequest can provide the function without reloading the page. When the page is loaded, the web page is updated, the client requests data from the server after the page is loaded, the server receives the data after the page is loaded, and sends data to the client in the background.
2.3.1. Method:
(1)overrideMimeType("text/html"):
Will override the header sent to the server, forcing text/xml as the mime-type
(2) open(method, url, async, username, password):
Initialize HTTP request parameters, such as URL and HTTP method, but do not send the request.
method parameter is the HTTP method used for the request, including GET, POST and HEAD;
url parameter is the body of the request
async parameter indicates whether the request uses synchronous or asynchronous, false request is synchronous, true request is The asynchronous
username and password parameters are optional and provide authentication qualifications for the authorization required by the url. If specified, they override any qualifications specified by url itself.
(3)send(body):
Send an HTTP request, using the parameters passed to the open() method, and the optional request body passed to the method
send(body) If by calling open() ) The specified HTTP method is POST or PUT, and the body parameter specifies the request body, as a string or Document object. If the request body is not required, this parameter will be null.
If the async parameter of the previously called open() is false, this method will block and will not return until readyState is 4 and the server's response is fully received.
If the async parameter is true, or this parameter is omitted, send() returns immediately, and as described later, the server response will be processed in a background thread
(4)setRequestHeader(name, value):
Sets or adds an HTTP request to an open but unsent request
The name parameter is the name of the header to be set. This parameter should not include whitespace, colons, or newlines.
The value parameter is the value of the header. This parameter should not include newlines
2.3.2. Attributes:
(1)onreadystatechange:
The event handler function called every time the readyState attribute changes. It may also be called multiple times when readyState is 3.
(2)readyState:
The status of the HTTP request. When an XMLHttpRequest is first created, the value of this attribute starts from 0 until a complete HTTP response is received, and the value increases to 4.
Each of the 5 states has an associated informal name. The following table lists the states, names and meanings:
The value of readyState will not be decremented except when a request is being processed The abort() or open() method is called during the process. Each time the value of this property is increased, the onreadystatechange event handler is triggered.
(3)status:
The HTTP status code returned by the server, such as 200 for success, and 404 for "Not Found" error. Reading this property when readyState is less than 3 will cause an exception.
(4)responseText:
The response body (excluding headers) received from the server so far, or an empty string if no data has been received yet.
If readyState is less than 3, this property is an empty string.When readyState is 3, this property returns the response part that has been received so far. If readyState is 4, this property holds the complete response body.
If the response contains a header specifying the character encoding for the response body, use that encoding. Otherwise, Unicode UTF-8 is assumed
(5)responseXML: Response to the request, parsed to XML and returned as a Document object
Code example:
Note: This example consists of a frontend and a backend , the backend uses servlet implementation, but does not go to the database to verify the data. The front desk is composed of html and javascript. The front desk verification adopts two methods. One is to use ajax encapsulated by jquery to realize the dynamic verification of the form. The second is to use the XMLHttpRequest object to realize the dynamic verification of the form. The difference between the two verification methods is just that the javascript script is different. , the front page and the background servlet are the same.
Front-end ajax.html
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
< ;/head>
Username:
Background AJAXServer.java:
import javax.servlet.http.HttpServlet;
import javax.servlet.http. HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
public class AJAXServer extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out= response.getWriter();
//1. Get parameters
String old=request.getParameter("name");
//2. Check if there is a problem
if(old==null ||old.length()==0){
out.println("User name cannot be empty");
}else{
//3. Verification operation
String name= old;
if(name.equals("pan")){
//4. Differences from traditional applications. This step requires returning the data that the user is interested in to the page, rather than to a new page
out.println("Username[" name "] already exists");
}else{
out .println("Username[" name "] can be used");
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request,response);
}
}
javascript:verify.js
function verify1(){
//1. Get Content in the text box
//document.getElementById("username");
var jqueryObj= $("#username");
//Get the value of the node
var userName=jqueryObj. val();
//2. Send the data in the text box to the server's servlet
$.get("AJAXServer?name=" username,null,callback);
}
function callback(data){
//3. Receive the data returned by the server
//4. Dynamically display the data returned by the server on the page
//Find the node that saves the information
var resultObj=$("#result");
resultObj.html(data);
}
//Verification method 2 is to write verification method 1 in a method, the effect is the same, both It is ajax dynamic verification form data encapsulated by jquery
function verify2(){
$.get("AJAXServer?name=" $("#username").val(),null,function(data) {
$("#result").html(data);
});
}
var xmlhttp;//Define a global variable
function verify3(){
//1. Use dom to get the value of the attribute in the text box
var username=document.getElementById("username").value;
//2. Create an XMLHttpRequest object
//You need to write different codes in different ways to create this object based on the differences between IE and other types of browsers
if (window. Fix the BUG of the browser
if(xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType("text/html");
}
} else if(window.ActiveXObject){
// For IE6, IE5.5, IE5
//Two control names used to create XMLHttpRequest objects, stored in a js array, the front version is newer
var activexName=["MSXML2.XMLHTTP ","Microsoft.XMLHTTP"];
for(var i=0;i
/ /If the creation fails, an exception will be thrown, and then you can continue to loop and continue to try to create
try{
xmlhttp=new ActiveXObject(activexName[i]);
break;
}catch(e) {
}
}
}
if(!xmlhttp){
alert("XMLHttpRequest object creation failed! ! ");
return;
}
//3. Register the callback function. When registering the callback function, only the function name is required, do not add brackets
//We need to register the function name. If you add brackets, the return value of the function will be registered, which is wrong
xmlhttp.onreadystatechange=callback3;
//4. Set the connection information
xmlhttp.open("GET","AJAXServer?name =" username,true);
//5. Send data and start interacting with the server
xmlhttp.send(null);//The username is encapsulated in the GET method url, so you only need to send one null
//POST method to request and send data
}
//Callback function
function callback3(){
//Determine whether the interaction of the object’s status is completed
if(xmlhttp.readyState==4){
//Determine whether the http interaction is successful
if(xmlhttp.status== 200) {
//Get the data returned by the server
//The first way: get the plain text data output by the server
var responseText=xmlhttp.responseText;
//Display the data Find the element node corresponding to the div tag on the page through dom
var divNode=document.getElementById("result");
//Set the content of html in the element node
divNode.innerHTML=responseText ;
}
}
}
web.xml
xsi:schemaLocation="http://java.sun.com /xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
web.xml

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

How to use Ajax functions to achieve asynchronous data interaction With the development of the Internet and Web technology, data interaction between the front end and the back end has become very important. Traditional data interaction methods, such as page refresh and form submission, can no longer meet user needs. Ajax (Asynchronous JavaScript and XML) has become an important tool for asynchronous data interaction. Ajax enables the web to use JavaScript and the XMLHttpRequest object

Understanding the Ajax Framework: Explore five common frameworks, requiring specific code examples Introduction: Ajax is one of the essential technologies in modern web application development. It has become an indispensable part of front-end development because of its features such as supporting asynchronous data interaction and improving user experience. In order to better understand and master the Ajax framework, this article will introduce five common Ajax frameworks and provide specific code examples to help readers gain an in-depth understanding of the usage and advantages of these frameworks. 1. jQuery jQuery is currently the most

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.
