Home Backend Development XML/RSS Tutorial Detailed explanation of XMLHTTP object encapsulation technology sample code

Detailed explanation of XMLHTTP object encapsulation technology sample code

Mar 27, 2017 pm 04:32 PM

The implementation of ajax technology mainly relies on xmlhttprequest, but when we call it for asynchronous data transmission, since xmlhttp is a short-term process (it is destroyed after the event processing is completed), if the object is not packaged, it has to be processed in Reconstructing xmlhttprequest where it needs to be called requires writing a large section of code for each call, which is really not a good idea. Fortunately, many open source ajax frameworks now provide solutions for encapsulating xmlhttp. Here we use the prototype-1.4.0.js that comes with ajaxtags as the master to see how to encapsulate the xmlhttp object into a reusable method.

In prototype.js, we first define a variable: Ajax

  var Ajax = {
    getTransport: function() {
     return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false;
  },
   
   activeRequestCount: 0
}
Copy after login

The variable returns an xmlhttprequest. You can see that if we call Ajax.getTransport(), it will be returned every time A new xmlhttprequest object.

A basic method Ajax.Base and the prototype of the basic method are defined in the Ajax variable (initially, each script method has an empty prototype by default, which will inherit the prototype of Object. If we If the prototype is changed in Object, all script methods will be changed) This basic method is inherited by Ajax.Request. Note that if the inherited prototype's method or variable with the same name is filled in Ajax.Request, it will be changed. Implement overloading.

The most important thing in the Ajax.Base prototype is the setOptions method, which we will use later.

setOptions: function(options) {
   this.options = {
    method:    'post',
    asynchronous: true,
    parameters:  ''
   }
Copy after login

The request in prototype is implemented by defining the Ajax.Request prototype (Ajax.Request.prototype). But we cannot directly call Ajax.Request. The main reason is that Ajax.Request does not provide a unified processing process. And we may need to obtain the response through the request. (Imagine that the customer sent a message but never received a reply. That would be very annoying~) The prototype also encapsulates the response (Ajax.Responders) for us, but both They are independent of each other. How to integrate them?

We are provided with two solutions in the prototype, one is Ajax.Updater and the other is Ajax.PeriodicalUpdater. The two have in common that 3 parameters must be passed in:

container :

The position where the response data is to be conveyed. The position is defined by the id of the html tag. For example, if you want to output the returned data to a

in html, you only need to change the container to this The value of id is enough. If the container is not found, a script error occurs.

url: The destination to which the

request request is to be passed. The destination should be a servlet or jspservlet, because the request object can only be automatically obtained by the do*** method in the servlet.

options:

The structure should be the same as the option structure in setOptions() defined by Ajax.Base above. If it is empty or not written, the initial value defined by Ajax.Base will be used (none used when passing any parameters).

The difference between the two is that Ajax.Updater returns the complete responseText to the container. Only when the responseText is completely obtained and no exception occurs, the content will be written to the container. When PeriodicalUpdater obtains the responseText, Regardless of whether it has been completely obtained, the content is filled into the container until an exception occurs or the responseText is completely obtained. In most cases, the first method should be used, because the first method will display the exception information in the container when an exception occurs, while the second method may not.

Now that xmlhttp has been encapsulated, we only need to set the three parameters mentioned above. It should be noted that when setting the options parameters, we must set them according to the options structure in the base. If we use the post method, we can also set the postBody attribute in opitons and put the queryString to be transferred in the body. An example of a script using the post method to transfer is as follows:

/*表单提交用post方法*/
function doRequest(container,paraments,url){
   var options ={
    method:    'post',
    asynchronous: true,
    postBody: paraments
   };
   new Ajax.Updater(container,url,options);  
}
Copy after login

The last thing I have to say is Chinese Encoding issues, the prototype performs encoding conversion on the passed parameters, and each passed value is processed through encodeURIComponent. The encoding will be converted to utf-8. When obtaining the request in the background, you should uniformly use request.setCharacterEncoding("UTF-8") to set the encoding for the request, regardless of the encoding format of the page. If you use the post method to transfer data, it will automatically execute:

request. setHeader('Content-type','application/x-www-form-urlencoded'). Ensure that the encoding format of the transmitted data is correct.

The above is the detailed content of Detailed explanation of XMLHTTP object encapsulation technology sample code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

HTTP 200 OK: Understand the meaning and purpose of a successful response HTTP 200 OK: Understand the meaning and purpose of a successful response Dec 26, 2023 am 10:25 AM

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

http request 415 error solution http request 415 error solution Nov 14, 2023 am 10:49 AM

Solution: 1. Check the Content-Type in the request header; 2. Check the data format in the request body; 3. Use the appropriate encoding format; 4. Use the appropriate request method; 5. Check the server-side support.

How to use PHP functions to process XML data? How to use PHP functions to process XML data? May 05, 2024 am 09:15 AM

Use PHPXML functions to process XML data: Parse XML data: simplexml_load_file() and simplexml_load_string() load XML files or strings. Access XML data: Use the properties and methods of the SimpleXML object to obtain element names, attribute values, and subelements. Modify XML data: add new elements and attributes using the addChild() and addAttribute() methods. Serialized XML data: The asXML() method converts a SimpleXML object into an XML string. Practical example: parse product feed XML, extract product information, transform and store it into a database.

How to implement HTTP streaming using C++? How to implement HTTP streaming using C++? May 31, 2024 am 11:06 AM

How to implement HTTP streaming in C++? Create an SSL stream socket using Boost.Asio and the asiohttps client library. Connect to the server and send an HTTP request. Receive HTTP response headers and print them. Receives the HTTP response body and prints it.

What status code is returned for an HTTP request timeout? What status code is returned for an HTTP request timeout? Feb 18, 2024 pm 01:58 PM

The HTTP request times out, and the server often returns the 504GatewayTimeout status code. This status code indicates that when the server executes a request, it still fails to obtain the resources required for the request or complete the processing of the request after a period of time. It is a status code of the 5xx series, which indicates that the server has encountered a temporary problem or overload, resulting in the inability to correctly handle the client's request. In the HTTP protocol, various status codes have specific meanings and uses, and the 504 status code is used to indicate request timeout issues. in customer

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

See all articles