Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Asynchronous Refresh function of Ajax

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "Ajax asynchronous refresh function example analysis", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn the "Ajax asynchronous refresh function example analysis" bar!

Let's first talk about the $_ GET request and the $_ POST request.

Methods:

Open (method,url,async)

Send (string)

Among them

Specifies the type of request, URL, and whether to process the request asynchronously.

Method: type of request; GET or POST

Url: location of the file on the server

Async:true (Asynchronous) or false (synchronous)

Send the request to the server.

String: for POST requests only

GET request

Methods:

Xmlhttp.open ("GET", "ajax_info.txt", true); xmlhttp.send ()

Some other comments about the GET request:

GET requests can be cached

GET requests are kept in the browser history

GET requests can be collected as bookmarks

GET requests should not be used when processing sensitive data

GET request has a length limit

GET requests should only be used to retrieve data (not modified)

POST request

Methods:

Xmlhttp.open ("POST", "/ try/ajax/demo_post.php", true); xmlhttp.send ()

Some other comments about the POST request:

POST requests will not be cached

POST requests are not retained in the browser history

POST cannot be collected as a bookmark

There is no requirement for data length in POST request

To sum up, that is,

GET is harmless when the browser rollback, and POST will submit the request again

The URL address generated by GET can be Bookmark, but POST cannot

The GET request will be actively cache by the browser, while the POST will not, unless set manually.

GET requests can only be encoded with url, while POST supports multiple encodings.

The GET request parameters will be fully preserved in the browser history, while the parameters in POST will not be retained.

The parameters passed by the GET request in the URL are limited in length, while the post does not.

GET only accepts ASCII characters for the data types of parameters, while POST has no restrictions

GET is less secure than POST because parameters are directly exposed to the URL, so they cannot be used to pass sensitive information.

The GET parameter is passed through URL, and the POST is placed in Request body.

We will use both methods in the following case, and you can observe the difference between the two.

A few knowledge points that will be used in a moment:

1. Xmlhttp.readyState==4 & & xmlhttp.status==200

The format used in the code in this section is

If (xhr.readyState = = 4) {if (xhr.status = = 200) {var result = xhr.responseText; var username_result = document.querySelector ("# username_result") If (result = = "ok") {username_result.innerText = "username can be used";} else {username_result.innerText = "username is already registered" }}}

So what do the words readyState and status mean?

The value and explanation of xmlhttp.readyState:

0: the request is not initialized (open () has not been called yet).

1: the request has been established, but has not been sent (send () has not been called yet).

2: the request has been sent and is being processed (usually the content header can now be obtained from the response).

3: the request is being processed; usually some data is available in the response, but the server has not finished generating the response.

4: the response is complete; you can get and use the server's response.

The value and explanation of xmlhttp.status:

100buy-the customer must continue to make requests

101Mel-the customer requires the server to convert the HTTP protocol version according to the request

200Mutual-deal succeeded

201Mui-prompt to know the URL of the new file

202 color-accept and process, but processing is not completed

203mer-the return information is uncertain or incomplete

204music-request received, but the return message is empty

205Mel-the server has completed the request, and the user agent must reset the currently browsed file

206Mel-the server has completed the GET requests of some users

300mura-requested resources are available in multiple places

301mer-Delete request data

302mi-request data was found at another address

303mer-customers are advised to visit other URL or access methods

304Mel-the client has executed GET, but the file has not changed

305music-the requested resource must be obtained from the address specified by the server

306Mel-the code used in the previous version of HTTP, no longer used in the current version

307 music-declare that the requested resource is temporarily deleted

400m-incorrect request, such as syntax error

401 color-request for authorization failed

402 color-keep valid Chargeto header response

403muri-request not allowed

404Mel-No files, queries, or URl found

405Mel-the method defined by the user in the Request-Line field is not allowed

406Mel-the requested resource is inaccessible based on the Accept sent by the user

407 Mel-similar to 401, users must first be authorized on the proxy server

408Mel-the client did not complete the request within the hungry time specified by the user

409 color-the request could not be completed for the current resource status

410Mel-this resource is no longer available on the server and there is no further reference address

411Mel-the server rejects a user-defined request for Content-Length attributes

412Mel-one or more request header fields are incorrect in the current request

413Mel-the requested resource is larger than the size allowed by the server

414Mel-the requested resource URL is longer than the length allowed by the server

415Mel-request resource does not support request project format

416 range-the request contains the Range request header field, there is no range indication value within the scope of the current request resource, and the request does not contain the If-Range request header field

417Mel-the server does not meet the expected value specified in the request Expect header field. If it is a proxy server, it may be that the server at the next level cannot meet the request.

Put it together

500mura-an internal error occurred on the server

501Mel-the server does not support the requested function

502Mel-the server is temporarily unavailable, sometimes to prevent system overload

503mura-server overload or suspension of maintenance

504Mel-the gate is overloaded and the server uses another gate or service to respond to the user. The set value of waiting time is long.

505Mel-the server does not support or reject the HTTP version specified in the request header

1xx: an information response class that indicates that a request has been received and processing continues

2xx: successfully handles the response class, indicating that the action is successfully received, understood, and accepted

3xx: redirects the response class, which must be further processed in order to complete the specified action

4xx: client error, customer request contains syntax error or cannot be executed correctly

5xx: server side error, the server cannot correctly execute a correct request

Explanation of xmlhttp.readyState==4 & & xmlhttp.status==200: request completed and returned successfully

2. Compatible processing for browsers of IE6 and below: var xhr = null; if (window.XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ("Microsoft.XMLHTTP")}

It's all written in a fixed way, so you don't have to remember it, or even write it in the code.

3. Onblur event

The onblur event occurs when the object loses focus.

Username.onblur = function () {}

This means that when the mouse cursor moves away from the current target and clicks somewhere else, the action in function is performed.

Operation demonstration

If the information we enter is legal and can be used after querying in the database

If the information we enter is already in the database, such as a nickname or a mobile phone number has been used

Of course, instead of using the database here, we use the if...else statement in the php code to make a simple judgment.

Next, let's take a look at the most important part-the code part.

HTML code

Wellfancy _ window.onload = function () {var username = document.querySelector ("# username"); var email = document.querySelector ("# email"); var phone = document.querySelector ("# phone"); username.onblur = function () {var usernameValue = username.value / / submit the usernamevalue to the server for uniqueness verification / / 1, create object compatibility processing (for IE6 and below, you may not write) var xhr = null; if (window.XMLHttpRequest) {xhr = new XMLHttpRequest () } else {xhr = new ActiveXObject ("Microsoft.XMLHTTP")} / / 2. Ready to send, note that the get method is used here, because the back-end php file uses get here, if the back-end engineer uses the post method Here, replace it with post xhr.open ("get", ". / Server1/checkUsername.php?uname=" + usernameValue,true). / / 3. Execute send xhr.send (null) / / make the callback function xhr.onreadystatechange = function () {/ / Note here is the fixed writing method if (xhr.readyState = = 4) {if (xhr.status = = 200) {var result = xhr.responseText / / do a local refresh below: var username_result = document.querySelector ("# username_result"); if (result = = "ok") {username_result.innerText = "user name can be used" } else {username_result.innerText = "user name has been registered";}};} Email.onblur = function () {var emailValue = email.value; var xhr = null; if (window.XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ("Microsoft.XMLHTTP") } var param = "e =" + emailValue; xhr.open ("post", ". / Server1/checkEmail.php", true); xhr.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xhr.send (param) Xhr.onreadystatechange = function () {if (xhr.readyState = = 4) {if (xhr.status = = 200) {var result = xhr.responseText; var email_result = document.querySelector ("# email_result") If (result = = 0) {/ / mailbox available email_result.innerText = "mailbox can be used";} else {email_result.innerText = "mailbox cannot be used" };}; phone.onblur = function () {var phoneValue = phone.value; var xhr = null; if (window.XMLHttpRequest) {xhr = new XMLHttpRequest () } else {xhr = new ActiveXObject ("Microsoft.XMLHTTP");} xhr.open ("post", ". / Server1/checkPhone.php", true); var params = "phonenumber=" + phoneValue; xhr.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded") Xhr.send (params); xhr.onreadystatechange = function () {if (xhr.readyState = = 4) {if (xhr.status = = 200) {/ / xhr.responseText is a string var result = xhr.responseText / / We want to convert a string like result into an object, so it is convenient for us to get some values result = JSON.parse (result); var phone_result = document.querySelector ("# phone_result") If (result.status = = 0) {/ / represents the mobile phone number available phone_result.innerText = result.message.tips + "," + result.message.phonefrom } else if (result.status = = 1) {/ / indicates that the mobile phone number is not available phone_result.innerText = result.message;} };}; user name of registration interface:

Mailbox:

Mobile phone number:

Php code section:

1. CheckUsername part:

2. CheckEmail part 3, checkPhone part

At this point, I believe that everyone on the "Ajax asynchronous refresh function example analysis" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report