Understanding Ajax, Part 1: Using dom

Source: Internet
Author: User
Tags image flip microsoft frontpage

The watershed between programmers (using backend applications) and web programmers (compiling HTML, CSS, and JavaScript) is long-lasting. However, the Document Object Model (DOM) makes up for this crack, making it extremely effective to use HTML at the front end while using XML at the back end. In this article, Brett McLaughlin introduces the Document Object Model, explains its application in web pages, and starts to explore its usage in JavaScript.

Like many web programmers, you may have used HTML. HTML is the way programmers start to deal with Web pages. html is usually the last step before they finish the application or site-adjust some la S, colors, or styles. However, although HTML is often used, there are common misunderstandings about what happened when HTML is displayed on the screen in a browser. Before analyzing what you think may happen and the possible causes of errors, I want you to understand the process involved in designing and serving web pages:

  1. Some people (usually you !) Create HTML in a text editor or IDE.
  2. Then you upload HTML to a Web server, such as Apache httpd, and publish it on the internet or intranet.
  3. The user requests your web page using Firefox, Safaria, and other browsers.
  4. Your browser requests HTML from your server.
  5. The browser displays the page received from the server in graphics and text format. The user can view and activate the web page.

This seems very basic, but things will soon become interesting. In fact, a huge number of "stuff" occurs between step 4 and step 5, which is the focus of this article. The term "padding" is also very useful, because most programmers have never really considered what happened to the tag when the user's browser requests display the tag.

  • Does the browser only read and display the text in HTML?
  • What about CSS? Especially when CSS is in an external file.
  • What about JavaScript? It is also usually located in an external file.
  • How does the browser handle these items if it maps event handlers, functions, and styles to the text tag?

Practice has proved that all these questions are answered by the Document Object Model. Therefore, do not talk about Dom directly.

Web programmers and tags

For most programmers, their work ends when Web browsers start. That is to say, after you put an HTML file in the directory of a Web browser, you usually think that it has been completed, and (hopefully) think thatNever consider it again! This is also a great goal when it comes to writing clean and well-organized pages. We hope that you can mark cross-browser pages and display the content that should be displayed with various versions of CSS and JavaScript, no error at all.

The problem is that this method limits the programmer's understanding of what actually happens in the browser. More importantly, it limits your ability to dynamically update, modify, and reconstruct web pages with client JavaScript. With this restriction, your web site can be more interactive and creative.

What do programmers do

As a typical web programmer, you may start text editing and IDE before entering HTML, CSS, and even JavaScript. It is easy to think that these tags, selectors, and attributes are just small tasks that make the site correctly displayed. However, you need to expand your thinking and realize that you are organizing your content. Don't worry; I promise this won't turn into a lecture on how to mark the appearance, how you must recognize the real potential of web pages, or any other metamaterial. You need to know what role you are playing in Web development.

When it comes to the page appearance, you can only provide suggestions. When you provide a CSS style sheet, you can overwrite your style selection. You provide a font size that your browser can change for the blind or scale down proportionally on a large display (with the same resolution. Even the color and font you select are subject to the user's display and font installed on the user's system. Although it is good to do your best to design the page styleNeverYou have the greatest impact on Web pages.

What you absolutely control is the Web PageStructure. Your mark cannot be changed, and the user cannot be confused; their browsers can only retrieve tags from your web server and display them (although the style is more in line with user taste than your own taste ). However, the page organization, whether in this section or in other partitions, is only determined by you. If you want to actually change your page (which is the focus of most Ajax applications), you operate on the page structure. Although it is easy to change the color of a piece of text, it is much harder to add text or the entire section on an existing page. No matter how you design the style of the section, you control the organization of the page itself.

Mark what to do

Once you realize that your tag is really related to the organization, you will see it differently. Not Consideredh1As a result, the text is large, black, and boldh1Is the title. What do users think about this problem and whether they use your CSS, their own CSS, or the combination of the two are secondary considerations. On the contrary, you must realize that only tags can provide organizations of this level;pSpecifies that the text is in the paragraph,imgIndicates the image,divDivide the page into segments.

It should also be clear that the style and behavior (event handler and JavaScript) are inEx postApplied to the Organization. You can only operate on or design a style after you mark it as ready. Therefore, just as you can save CSS in an HTML external file, the tag organization is separated from its style, format, and behavior. Although you can certainly use JavaScript to change the element or text style, it is more interesting to actually change the organization of your tag.

As long as you keep in mind that your tag only provides organization and framework for your page, you will be undefeated. One small step further, you will understand how the browser accepts all the text organizations and converts them into something super interesting, that is, a group of objects, each object can be changed, added, or deleted.

Other ideas about tagging

Edit plain text: Right?
Text is ideal for storing tags, but not suitableEditMark. IDE, such as Macromedia Dreamweaver or Microsoft FrontPage, is widely used to operate web page tags. These environments usually provide shortcuts and help to create web pages, especially when CSS and JavaScript are used, they both come from files other than the actual page tag. Many people still prefer to use old notebooks or VI (I admit I am one of them), which doesn't matter. In any case, the final result is a text file filled with markup.

Text on the Network: good stuff
As we have already said, text is the best media for a document, such as HTML or CSS, which is transmitted over the Internet thousands of times. When I say that it is difficult for a browser to express text, it refers to converting text into a visual image page that users can view. This has nothing to do with how the browser actually retrieves pages from the web browser; in this case, text is still the best choice.

Advantages of text tagging

Before discussing Web browsers, it is worth considering why plain textAbsoluteIs the best choice for storing HTML (for more information, see some other ideas about tag ). Without considering the advantages and disadvantages, I just recall that HTML is sent to the Web browser through the network every time I view the page (for simplicity, I do not consider high-speed caching, etc ). There are no more effective methods than passing texts. Binary objects, graphic representation of pages, re-organized tag blocks, and so on, all of which are more difficult than passing plain text files over the network.

In addition, the browser also adds luster. Today's Browser allows users to change text size, scale images proportionally, download CSS or JavaScript on pages (in most cases), or even more, this completely eliminates the need to send any type of page graphical representation to the browser. However, the browser needs the original HTML so that it can apply any processing to the page in the browser, rather than trusting the browser to process the task. Similarly, separating CSS from JavaScript and separating CSS from HTML tags requires a format that is easy to separate. Text Files once again become the best method for this task.

Last but equally important, remember that the new standard (such as HTML 4.01 and XHTML 1.0 and 1.1) promises to include content (data in the page) and representation and style (usually applied by CSS) separated. If the programmer wants to separate HTML from CSS and then forces the browser to search for some page representations of each part of the bonded page, this will lose most of the advantages of these standards. Keeping these parts separated when they arrive at the browser gives the browser unprecedented flexibility in getting HTML from the server.

Learn more about Web browsers

For some web programmers, all the content read above may be a funny story about your role during web development. But when it comes to browser behavior, many of the most competent web designers and developers are usually not aware of the "Inside" situation. I will focus on this section. Don't worry, the code is coming soon, but you need to restrain your impatience in coding, because it is critical to really understand the exact behavior of Web browsers for your code to work correctly.

Disadvantages of text tagging

Just as text markup has amazing advantages for designers and page creators, it also has surprising disadvantages for browsers. Specifically, it is difficult for a browser to directly present text tags to users visually (for more information, see some other ideas about tagging ). Consider the following common browser tasks:

  • Apply CSS styles (usually from multiple style sheets in external files) to tags Based on element types, classes, IDs, and their locations in HTML documents.
  • Apply styles and formats to different parts of HTML documents based on JavaScript code (usually in external files.
  • Modify the value of a form field based on JavaScript code.
  • Based on JavaScript code, it supports visual effects, such as image flip and image exchange.

The complexity is not about coding these tasks; everything is quite easy. Complexity comes from browsers that actually implement request actions. If the tag is stored as text, for example, you wantcenter-textClasspInput text in the element (text-align: center), How to implement it?

  • Add inline styles to text?
  • Apply the style to HTML text in the browser and keep the content centered or not centered?
  • Apply the HTML without a style, and then apply the format afterwards?

These very difficult problems are the cause of few browsers today. (The person who wrote the browser should accept the most sincere thanks)

Without a doubt, plain text is not a good way to store browser HTML, although text is the best solution for getting page tags. If Javascript is addedChangeThe page structure becomes more subtle. Should the browser rewrite the modified structure to the disk? How can we maintain the latest version of the document?

No doubt, text is not the answer. It is difficult to modify, and it is very difficult to apply styles and behaviors for it. It is fundamentally different from the dynamic nature of today's web pages.

Turn to Tree View

The answer to this question (at least the answer selected by today's Web browsers) is to use a tree structure to represent HTML. See Listing 1. This is a simple and boring HTML page.

Listing 1. simple HTML page in text tag

The browser accepts the page and converts it to a tree structure, as shown in 1.

Figure 1. Tree View in Listing 1

To keep the progress of this article, I have simplified it a little. Dom or XML experts will be aware of the impact of blank spaces on the representation and decomposition of document text in the Web browser tree structure. Superficial Understanding can only make things ambiguous, so if you want to figure out the influence of the blank, you 'd better not think about it. If you don't want to, you can continue to read it. When it becomes a problem, you will understand everything you need.

In addition to the actual tree background, you may first notice that everything in the tree contains elements in the outermost HTML, that ishtmlElement. The tree metaphor is calledRoot element. So even if this is the bottom layer of the tree, When you view and analyze the tree, I usually start with this. If it does, you can turn the entire tree upside down, but it does extend the tree metaphor.

The line from the root represents the relationship between different marked parts.headAndbodyElement ishtmlRoot elementChild;titleYesheadWhile the text "trees, trees, everywhere" istitle. The entire tree is organized in this way until the browser obtains a structure similar to figure 1.

Additional Terms

To use the tree metaphor,headAndbodyCalledhtmlOfBranches). They are called branches because they have their own children. When you reach the end of the tree, you will enter the main text, such as "trees, trees, everywhere" and "really ".LeafBecause they do not have their own children. You don't need to remember all these terms. When you try to figure out the meaning of a specific term, it's much easier to think about the tree structure.

Object Value

Now that you understand some basic terms, you should take a look at the small rectangle containing the element name and text (figure 1 ). Each rectangle is an object. The browser solves some text problems. By using objects to represent each part of an HTML document, you can easily change the organization, apply the style, and allow JavaScript to access the document.

Object Type and attribute

Each possible type of the tag has its own object type. For exampleElementObject type. Text in the documentTextType.AttributeType, and so on.

Therefore, Web browsers can not only use object models to represent documents (thus avoiding static text processing), but also use object types to immediately identify what a thing is. The HTML document is parsed and converted to an object set, as shown in Figure 1. Then, angle brackets and escape sequences (for example, use<Indicates<, Use>Indicates>. This makes it easier for the browser to work (at least after parsing the input html. It is easy to find out whether a thing is an element or an attribute and determine how to process the type of object.

By using objects, Web browsers can modify the attributes of these objects. For example, each element object has a parent element and a series of child elements. Therefore, to add a new child element or text, you only need to add a new child element to the child element list of the element. These objects also havestyleSo it is very easy to quickly change the style of an element or text segment. For example, to use JavaScript to changedivIs as follows:

someDiv.style.height = "300px";

In other words, Web browsers can easily change the tree's appearance and structure by using object properties. It is similar to the complex things that must be performed when the browser internally expresses the page as text. Every time you change the attribute or structure, the browser needs to re-compile the static file, re-parse the file, and re-display it on the screen. With the object, all this is done.

Now, take some time to expand some HTML documents and sketch them out in a tree. Although this looks like an unusual request (especially in an article that contains very little code), if you want to manipulate these trees, you need to be familiar with their structure.

In this process, you may find some strange things. For example, consider the following situations:

  • What happened to the property?
  • Decomposed into elements (suchemAndb) Text?
  • Incorrect structure (for example, when the end is missingpWhat about html?

Once you are familiar with these problems, you can better understand the following sections.

Strict and sometimes good

If you try exercise I, you may find some potential problems in the marked Tree View (if you do not want to practice it, let me know !). In fact, some problems are found in Listing 1 and figure 1.pHow elements are decomposed. If you ask a common web developer"pWhat is the text content of an element? The most common answer is "Welcome to a really boring web page .". If you compare it with figure 1, you will find that this answer (although logical) is fundamentally incorrect.

Actually,pElement hasThreeDifferent sub-objects, none of which contain the complete "Welcome to a really boring web page." text. You will find part of the text, such as "Welcome to a" and "Boring Web page", but not all. To understand this, remember that everything in the tag must be converted to a certain type of object.

In addition, the order is irrelevant! If the browser displays the correct object, but the display order is different from the order you provided in HTML, how can you imagine the user responding to the Web browser? The Section is in the middle of the page title and article title, and this is not the style when you organize the document yourself? Obviously, the browser must keep the order of elements and text.

In this example,pThe element has three different parts:

  • emText before the element
  • emElement itself
  • emText after Element

If this order is disrupted, the emphasis may be placed on the text error section. To keep everything normal,pThe element has three child objects in the order displayed in the HTML of Listing 1. In addition, the key text "really"NopButpChild Elementem.

Understanding this concept is very important. Although the "really" text may be associated with otherpThe element text is displayed together, but it is stillemThe direct child element of the element. It can havepDifferent text formats, and can be moved everywhere independently of other texts.

Keep this in mind and try to use graphs to represent the HTML in Listing 2 and 3 to ensure that the text has the correct parent element (regardless of how the text will eventually be displayed on the screen ).

Listing 2. tags with cleverly nested Elements

Listing 3. More clever element nesting

The answers to these exercises will be found in the tricky-solution.gif in Figure 2 at the end of this article, GIF files, and the trickier-solution.gif in figure 3. Don't peek. Take some time to answer questions automatically. This helps you understand how strict the rules are applied in the organization tree, and truly help you grasp the HTML and its tree structure.

What about attributes?

When you try to figure out how to handle attributes, do you have any problems? As mentioned above, an attribute does have its own object type, but it is not a child element of its element. The nested element and text are not in the same attribute "level". You will notice that, the answers to exercises in Listing 2 and 3 do not show attributes.

Attributes are actually stored in the object model used by the browser, but they have some special situations. Each element has a list of available attributes separated from the list of sub-objects. SodivAn element may have a list containing the attribute "ID" and another attribute "class.

Remember, the attribute of an element must have a unique name. That is to say, an element cannot have two "IDS" or two "class" attributes. This makes the list easy to maintain and access. As you can see in the next article, you can callgetAttribute("id")To obtain the attribute value by name. You can also call it in a similar way to add a property or set (reset) the value of an existing property.

It is worth noting that the uniqueness of attribute names makes the list different from the sub-Object List.pThe element can have multipleemThe sub-Object List can contain multiple repeated items. Although the subitem list and attribute list are operated in a similar way, one can contain duplicate items (the subitem of an object), and the other cannot (the attribute of an element object ). Finally, only elements have attributes, So text objects do not have an additional list for storing attributes.

Messy html

Before proceeding, we will talk about how the browser converts tags into tree representations. Another topic worth exploring is how the browser handles poorly formatted tags.Good formatIt is a widely used term in XML and has two basic meanings:

  • Each start tag has a matched end tag. So each<p>In the document</p>Match, each<div>And</div>Match, and so on.
  • The Start mark in the innermost part matches the end mark in the innermost part, and the Start mark in the second matches the end mark in the second, and so on. So<b><i>bold and italics</b></i>It is invalid because the Start mark in the innermost part<i>And the ending mark in the innermost part<b>Improper matching. To make it in good format,OrSwitch start to mark the order,OrSwitch end tag order. (If both are switched, problems still occur ).

Study these two rules in depth. These two rules not only simplify the document organization, but also eliminate uncertainty. Should bold text be applied first and then italic text be applied? Or exactly the opposite? If you think this order and uncertainty are not a big problem, remember that CSS allows rules to overwrite other rules.bThe text font in the element is different fromiThe font in the element, the application order of the format will become very important. Therefore, the good HTML format plays an important role.

If the browser receives a document that is not in good format, it will do its best. In the best case, the resulting tree structure will be the approximate structure of the original page that the author wants. In the worst case, it will be completely invisible. If you have loaded the page into the browser and see a completely unexpected result, you may wonder how your structure should be and continue working with frustration when you see the browser result. Of course, it is quite simple to solve this problem: Make sure that the document is in good format! If you are not clear about how to compile standard HTML, please consult references for help.

Introduction to Dom

So far, you know that the browser converts a web page to an object representation. You may even guess that the object representation is a DOM tree. Dom indicates the Document Object Model, which is a standard and can be obtained from the World Wide Web Consortium (W3C) (see some Dom-related links in references ).

But more importantly, Dom defines the object type and attributes, allowing the browser to indicate the tag. (The next article in this series will detail how to use DOM in JavaScript and Ajax code .)

Document Object

First, you need to access the object model itself. This is very easy; use built-in in any JavaScript code running on the web pagedocumentVariable, you can write the following code:

var domTree = document;

Of course, this code is useless, but it demonstrates that every web browser makesdocumentThe object can be used in JavaScript code and demonstrates the complete tree of the object that represents the mark (figure 1 ).

Each item is a node

Apparently,documentObjects are very important, but this is just the beginning. Before further exploration, you need to learn another term:Node. You already know that each part of the tag is represented by an object, but it is not just an arbitrary object, it is a specific type of object, a DOM node. More specific types, such as text, elements, and attributes, all inherit from this basic node type. Therefore, there can be text nodes, element nodes, and attribute nodes.

If you already have a lot of JavaScript programming experience, you may already be using Dom code. If you have been tracking this Ajax series so farYesDom code has been used for some time. For example, the code linevar number = document.getElementById("phone").value;Use the Dom to search for a specific element and then retrieve the value of the element (in this example, it is a form field ). So even if you are not aware of thisdocumentDom is used when you type JavaScript code.

To explain in detail the terms that have been learned, the DOM tree is the object tree, but more specifically, it isNodeObject Tree. In Ajax applications or any other JavaScript, these nodes can be used to produce the following effects, such as removing elements and their content, highlighting specific text, or adding new image elements. Because it occurs on the client (the code running in the Web browser), these effects happen immediately without communicating with the server. The final result is usually that the application feels faster, because content changes on the Web page do not pause for a long time when the request is redirected to the server and the response is interpreted.

In most programming languages, you need to learn the actual object names of each node type, learn available attributes, and clarify the types and forced conversions. However, this is not necessary in JavaScript. You can create only one variable and assign it the object you want (as you can see ):

var domTree = document;var phoneNumberElement = document.getElementById("phone");var phoneNumber = phoneNumberElement.value;

No type. Javascript creates variables as needed and assigns them the correct type. As a result, the use of DOM in Javascript becomes insignificant (in the future there will be an article dedicated to the DOM related to XML, which will be more clever at that time ).

Conclusion

Here, I want to give you some suspense. Obviously, this is not a fully detailed description of Dom; in fact, this article is just an introduction to Dom. Dom has much more content than I have introduced today!

The next article in this series will expand these ideas and explore how to use DOM in JavaScript to update web pages, quickly change HTML, and create a more interactive experience for your users. In the subsequent articles devoted to using XML in Ajax requests, I will return to discuss Dom again. So be familiar with Dom, which is a major part of Ajax applications.

At this point, it will be very easy to understand the Dom, for example, how to move in the DOM tree, get the value of elements and text, traverse the node list, and so on, but this may give you the impression that Dom is about code, but not actually.

Before reading the next article, try to think about the tree structure and use some of your own HTML practices to see how the web browser converts HTML into a marked tree view. In addition, let's take a look at the DOM tree organization and use the special cases introduced in this article to practice: the text of the attribute and element in it,NoElements of text content (for exampleimgElement ).

If you have mastered these concepts and then learned the JavaScript and Dom syntax (next article), it will make the response easier.

And don't forget, here are the answers in Listing 2 and 3, which also contain the sample code!

Figure 2. Answer in Listing 2

Figure 3. Answer in listing 3

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.