search
HomeBackend DevelopmentXML/RSS TutorialDetailed explanation of XMLHTTP object encapsulation technology sample code

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
}

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:  ''
   }

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);  
}

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
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
Mastering Well-Formed XML: Best Practices for Data ExchangeMastering Well-Formed XML: Best Practices for Data ExchangeMay 14, 2025 am 12:05 AM

Well-formedXMLiscrucialfordataexchangebecauseitensurescorrectparsingandunderstandingacrosssystems.1)Startwithadeclarationlike.2)Ensureeveryopeningtaghasaclosingtagandelementsareproperlynested.3)Useattributescorrectly,enclosingvaluesinquotesandavoidin

XML: Is it still used?XML: Is it still used?May 13, 2025 pm 03:13 PM

XMLisstillusedduetoitsstructurednature,humanreadability,andwidespreadadoptioninenterpriseenvironments.1)Itfacilitatesdataexchangeinsectorslikefinance(SWIFT)andhealthcare(HL7).2)Itshuman-readableformataidsinmanualdatainspectionandediting.3)XMLisusedin

The Anatomy of an RSS Document: Structure and ElementsThe Anatomy of an RSS Document: Structure and ElementsMay 10, 2025 am 12:23 AM

The structure of an RSS document includes three main elements: 1.: root element, defining the RSS version; 2.: Containing channel information, such as title, link, and description; 3.: Representing specific content entries, including title, link, description, etc.

Understanding RSS Documents: A Comprehensive GuideUnderstanding RSS Documents: A Comprehensive GuideMay 09, 2025 am 12:15 AM

RSS documents are a simple subscription mechanism to publish content updates through XML files. 1. The RSS document structure consists of and elements and contains multiple elements. 2. Use RSS readers to subscribe to the channel and extract information by parsing XML. 3. Advanced usage includes filtering and sorting using the feedparser library. 4. Common errors include XML parsing and encoding issues. XML format and encoding need to be verified during debugging. 5. Performance optimization suggestions include cache RSS documents and asynchronous parsing.

RSS, XML and the Modern Web: A Content Syndication Deep DiveRSS, XML and the Modern Web: A Content Syndication Deep DiveMay 08, 2025 am 12:14 AM

RSS and XML are still important in the modern web. 1.RSS is used to publish and distribute content, and users can subscribe and get updates through the RSS reader. 2. XML is a markup language and supports data storage and exchange, and RSS files are based on XML.

Beyond Basics: Advanced RSS Features Enabled by XMLBeyond Basics: Advanced RSS Features Enabled by XMLMay 07, 2025 am 12:12 AM

RSS enables multimedia content embedding, conditional subscription, and performance and security optimization. 1) Embed multimedia content such as audio and video through tags. 2) Use XML namespace to implement conditional subscriptions, allowing subscribers to filter content based on specific conditions. 3) Optimize the performance and security of RSSFeed through CDATA section and XMLSchema to ensure stability and compliance with standards.

Decoding RSS: An XML Primer for Web DevelopersDecoding RSS: An XML Primer for Web DevelopersMay 06, 2025 am 12:05 AM

RSS is an XML-based format used to publish frequently updated data. As a web developer, understanding RSS can improve content aggregation and automation update capabilities. By learning RSS structure, parsing and generation methods, you will be able to handle RSSfeeds confidently and optimize your web development skills.

JSON vs. XML: Why RSS Chose XMLJSON vs. XML: Why RSS Chose XMLMay 05, 2025 am 12:01 AM

RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.

See all articles

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.