Ajax technology one, Ajax technology_PHP tutorial
Ajax technology one, Ajax technology
1, Ajax overview
1. Historical origins
In 1998, Microsoft's Outlook Web Access R&D team integrated a technology into the then IE browser that could send HTTP requests to the server without refreshing the client. This technology was called is "XMLHTTP".
In 2005, Google applied Ajax technology in many of its products (Gmail, Google Suggest search suggestions, Google Maps). From then on, Ajax became popular...
2. What is Ajax technology
- Asynchronous: asynchronous
- JavaScript: Javascript technology
- And: and
- XML: Extensible Markup Language, mainly used for data transmission and storage
The so-called Ajax technology is asynchronous Javascript and XML. Since XML is mainly used for data transmission and storage, it can be seen that the core of Ajax is asynchronous Javascript.
3. Web technology
Client language:
- Html
- Css
- Javascript
Server language:
- ASP (ASP.NET)
- JSP
- PHP
Since Ajax is asynchronous Javascript, we can be sure that Ajax also runs on the client browser.
4. Ajax working mode
1) Synchronous request:
When the network speed is relatively slow, the experience of synchronous requests is very unsatisfactory, because the user feels that the entire request is a discontinuous process.
2) Asynchronous request:
As can be seen from the above figure, when the user sends a request, the system first sends the request to the Ajax object. The Ajax object sends the request, and then the server processes the request, but the processing has not yet been completed. , it will return part of the data to the client, so for the user, the entire request is a continuous process, and the experience is very good.
5. Ajax application scenarios
① Form verification (real-time verification whether the username is unique)
② Baidu drop-down search
③ No refresh paging
④ WebAPP mobile PHP background program (mobile APP)
6. Quick Start
demo01_rumen.html
demo01.php
Run results:
2. Ajax object
1. Why do you need Ajax objects?
Remember: There is a prerequisite for using Ajax technology, you must create an Ajax object.
2. How to create an Ajax object
Based on IE core browser (IE browser below IE8, compatibility mode of various browsers)
var Ajax object = new ActiveXObject('Microsoft.XMLHTTP');
Based on W3C core browser (Firefox, Google Chrome, extreme speed mode of various browsers)
var Ajax object = new XMLHttpRequest();
3. Solve the compatibility problem of Ajax objects
① Create a public.js file as the core code base
② Define a $ function to obtain the DOM object with the specified id
③ Define a public function, such as createXhr(), for creating Ajax objects
4. Properties and methods in Ajax objects
Common methods
- open(method,url): Initialize the Ajax object (set the request type and request address)
- setRequestHeader(header,value): Set request header
Parameter description:
header: request header
value: value
- send(content): Send Ajax request
Parameter description:
content: Parameters passed in the blank line of the request. If it is a get request, this value is null
Common attributes
- onreadystatechange: The callback function triggered when the Ajax status code changes
- readyState: Ajax status code
0: Indicates that the object has been created but not initialized. The createXhr method has been called, but the open method has not been called.
1: Indicates that the object has been initialized but not sent. The open method has been called, but the send method has not been called.
2: The send method has been called to make a request
3: Receiving data (part of it received)
4: Reception completed
- status: response status code, 200 reception completed, 404 page not found
- statusText (understood): response status text
- reponseText: response result
- responseXML: response result
If the server returns a string, use xhr.responseText to receive it
If the server returns data in XML format, use xhr.responseXML to receive it
3. Get request in Ajax
1. Ajax formula: five steps for get request in Ajax
① Create Ajax object
② Set callback function
③ Initialize Ajax object
④ Send Ajax request
⑤ Judgment and execution
2. Use Ajax technology to send get requests
demo04.php
3. Use the get request in Ajax to pass the value
demo05.php
4. A few minor questions
1) Question: When we use Ajax, we find that we return data through echo statements on the server side. Can this place be replaced by return statements?
Answer: Although the echo statement and the return statement both have the meaning of return, the return positions of the two are different. The return statement returns data to the server, while the echo output mainly returns the output data to the client. (browser). Therefore, only the echo statement can be used on the server side and the return statement cannot be used.
2) Question: When sending an Ajax request, what will happen if the requested page does not exist?
Answer: If the server-side page we request does not exist, its Ajax will also return the following results:
However, in actual project development, if the above pop-up window appears, it will not be good for the user experience, so this behavior must be prohibited.
We can avoid the above situation by judging the server-side response status code:
The above code can also be further simplified into the following form:
3) Question: In actual project development, can the positions of the above judgment statements xhr.readyState==4 and xhr.status==200 be exchanged?
Answer: No, because in actual project development, the Ajax status code must be judged first. When it is 4, it means that the data returned by the server has been fully received, and status represents the time when readyState is equal to 4 is used to determine the server-side return status code, so the order between the two cannot be exchanged.
4) Question: How to debug Ajax during development?
① If it is an Ajax syntax error, we can capture it directly through the status bar of IE or the console in the Firebug plug-in in Firefox.
② Server-side error. If we find that the return result is abnormal during development, we can debug it through httpwatch or the network panel of the W3C browser.
httpwatch:
Firebug:
Google:
③ How to deal with logic errors encountered during development
5. Practical application: Use Ajax to verify whether the user name is unique
demo06.php
Note: In actual application cases, we can complete the verification of whether the user name is unique through Ajax PHP. However, when running, we found that the above case will cause caching problems under the IE browser, resulting in the request result Abnormal, how to solve this problem in actual project development?
4. Solve the caching problem in Ajax
1. What is IE cache?
When we send a get request to a certain URL address for the first time under the IE browser, the system will automatically cache the requested resource file and store it in the client browser. We will Just call it "IE cache".
2. IE cache function
Microsoft uses caching technology in its own IE browser to allow users to quickly obtain server-side response data.
Implementation process: After the IE browser caches the requested resource file, the system will automatically call the cached file the next time a request is sent to the same URL. However, there is also a shortcoming in practical application: if the server-side data is updated, then we cannot obtain the latest data in real time.
3. Solve the caching problem of get requests in Ajax technology
1) Use random numbers to solve caching problems
Run results:
Note: Although we can use random numbers to artificially change the URL address of the request, so that the URL of each request is inconsistent. However, random numbers cannot guarantee that the random numbers generated are unique every time, and duplicates may also occur. In addition, cache files will be generated every time a request is made, so random numbers will generate a large number of cache files on the client side.
2) Use timestamps to solve cache problems (key points)
In actual development, we know that timestamps will never be repeated, so we can use this method to solve the cache problem.
Run results:
Note: Although we can use timestamps to solve the caching problem, it will also generate a large number of cache files on the client.
3) Use the last modification time of the file to solve caching issues (Important)
Cache core mechanism:
If we want to solve the caching problem, we can artificially change the value of If-Modified-Since so that it is inconsistent with the server's resource file every time it is checked to solve the caching problem.
Run results:
Note: Although the above program can solve the cache problem, does it also generate a large number of cache files?
Answer: No, because the URL address we request every time is the same, so it will only generate one cache file. When the second request is made, the system will only update the cache file. Will not be regenerated.
4) Use the disable caching function to solve Ajax caching problems
You can add the following menu to the server-side page, so that you can tell the browser not to cache the current page, thereby solving the cache problem:
The main function of the header function is to tell the browser to perform certain operations. The above code means telling the browser not to cache the current page. It needs to re-obtain the latest data every time it is requested, thus fundamentally disabling caching.
Run results:
The above program fundamentally disables caching, the ultimate solution.
5. Post request in Ajax
1. The difference between get request and post request
① Different methods of passing parameters
The get request appends the parameters to the end of the URL when passing parameters.
When passing parameters in the post request, the parameters are appended to the request blank line position
② Different security
Post request is slightly more secure than get request
③ Parameter sizes are different when passing parameters
The maximum value when passing parameters in a get request is 2kb. In theory, there is no size limit for post requests. However, in actual project development, it is mainly affected by the php.ini file. Generally, the maximum value is 8M or 2M
④ The request header information is different
get request:
post request:
In comparison, the post request has one more request header information than the get request:
Content-type:application/x-www-form-urlencoded
2. Six steps for post requests in Ajax
Step 1: Create Ajax object
Step 2: Set the callback function
Step 3: Initialize the Ajax object
Step 4: Set request header information (set Content-type)
Step 5: Send Ajax request
Step 6: Judgment and Execution
demo08.php
3. Practical application: Using Ajax PHP to implement refresh-free login function
demo09.php
6. XML data in Ajax
1. What is XML
The so-called XML is extensible markup language, which mainly realizes the transmission and storage of large batches of data.
2. XML execution schematic diagram
PHP can implement XML parsing operations and provides a total of two solutions:
PHP DOM model (implementing addition, deletion and modification operations)
PHP SimpleXML model (implementing query operations)
1) PHP DOM model (non-standard DOM model)
① Open up memory space
② Load xml file into memory to form DOM tree structure
【Non-standard DOM model】
【Standard DOM Model】
The DOM model in Javascript is the standard DOM model. In practical applications, the main difference between the standard DOM model and the non-standard DOM model is:
Non-standard DOM model: Find a point à and output its value directly through the nodeValue attribute
Standard DOM model: Find a pointàFind its child nodeàOutput the text node value through the nodeValue attribute
3. Use Ajax XML to parse large batches of data
Example: Using Ajax XML to return the four arithmetic results of two numbers
Knowledge to be used:
childNodes: Get all child elements of the current element and return data
demo10.php

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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.

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

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:

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.

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

Ajax is not a specific version, but a technology that uses a collection of technologies to asynchronously load and update web page content. Ajax does not have a specific version number, but there are some variations or extensions of ajax: 1. jQuery AJAX; 2. Axios; 3. Fetch API; 4. JSONP; 5. XMLHttpRequest Level 2; 6. WebSockets; 7. Server-Sent Events; 8, GraphQL, etc.
