[Learn Ajax in four days] Use dom for Web response on the fourth day of the Ajax tutorial

Source: Internet
Author: User
Tags image flip microsoft frontpage
Like in HTML external files, the organizations marked are separated from their styles, formats, and behaviors. 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.

Advantages of text tagging

Before discussing Web browsers, it is worth considering why plain text is definitely the best choice for storing HTML (for more information, see other ideas about tagging ). 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.

Other ideas about tagging

Edit plain text: Right?
Plain text is ideal for storing tags, but it is not suitable for editing tags. 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.

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.
· Supports visual effects, image flip and image exchange based on JavaScript code.

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, if you want to input text (text-align: center) in the P element of the center-text class, how can we 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 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. With the ability of JavaScript to change the Page Structure, things become 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

<HTML>
<Head>
<Title> trees, trees, everywhere </title>
</Head>
<Body>
<H1> trees, trees, everywhere <P> welcome to a <em> really </em> boring page. </P>
<Div>
Come again soon.

</Div>
</Body>
</Html>

The browser accepts the page and converts it to a tree structure, as shown in 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 begins with the outermost HTML inclusion element, that is, the HTML element. The tree is called the root 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. The head and body elements are children of the HTML root element; the title is the child of the head, and the text "trees, trees, everywhere" is the child of the title. The entire tree is organized in this way until the browser obtains a structure similar to figure 1.

Additional Terms

To keep the tree analogy, head and body are called HTML branches ). 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"; these are usually called leaves because 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 example, elements in HTML are represented by the element object type. The text in the document is represented by the text type, the attribute is represented by the attribute type, 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, followed by Angle brackets and escape sequences (for example, use <representation <, use> representation>) and other things are no longer a problem. 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 have style attributes, so it is very easy to quickly change the style of elements or text segments. For example, you need to use JavaScript to change the DIV height, as shown below:

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?
· What about text decomposed into elements (such as Em and B?
· Is the structure incorrect (for example, when the end P tag is missing?

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 will be found in Listing 1 and figure 1. First, let's look at how P elements are decomposed. If you ask a common web developer "what is the text content of P elements", 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.

In fact, the P element has three different sub-objects, and none of them contains 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, the P element has three different parts:

· Text before em Elements
· Em element itself
· Text after em Elements

If this order is disrupted, the emphasis may be placed on the text error section. To keep everything normal, the P element has three sub-objects in the order shown in the HTML in Listing 1. Moreover, the key text "really" is not a child element of P, but a child element of the child element em of P.

Understanding this concept is very important. Although the "really" text may be displayed together with other P element texts, it is still a direct child element of the EM element. It can be in different formats from other P texts 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

<HTML>
<Head>
<Title> This is a little tricky </title>
</Head>
<Body>
<H1> PAY <u> close </u> attention, OK? </H1>
<Div>
<P> This P really isn't <em> necessary </em>, but it makes
<Span id = "bold-text"> structure <I> and </I> the Organization </span>
Of the page easier to keep up with. </P>
</Div>
</Body>
</Html>

Listing 3. More clever element nesting

<HTML>
<Head>
<Title> trickier nesting, still </title>
</Head>
<Body>
<Div id = "main-body">
<Div id = "contents">
<Table>
<Tr> <TH> steps </Th> <TH> Process </Th> </tr>
<Tr> <TD> 1 </TD> <TD> figure out the <em> root element </em>. </TD> </tr>
<Tr> <TD> 2 </TD> <TD> deal with the <span id = "code"> head </span> first,
As it's usually easy. </TD> </tr>
<Tr> <TD> 3 </TD> <TD> work through the <span id = "code"> body </span>.
Just <em> take your time </em>. </TD> </tr>
</Table>
</Div>
<Div id = "Closing">
This link is <em> not </em> active, but if it were, the answers
To this <a href = "answers.html"> </a> wowould
Be there. But <em> do the exercise anyway! </Em>
</Div>
</Div>
</Body>
</Html>

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. Therefore, the DIV 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 will see in the next article, you can call methods such as getattribute ("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. The P element can have multiple em elements, so the 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 format is a term widely used in XML, which has two basic meanings:

· Each start tag has a matched end tag. Therefore, each <p> matches </P> In the document, each <div> matches </div>, 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. Therefore, <B> <I> bold and italics </B> </I> is invalid, because the start Mark <I> in the innermost part does not match the end mark <B> in the innermost part. To make it in good format, either switch the start marking order or switch the end Marking 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. Therefore, for example, if the text font in element B is different from that in element I, then 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; to use the built-in document variable in any JavaScript code running on the web page, you can write the following code:

VaR domtree = document;

Of course, this code is useless, but it demonstrates that each web browser makes the Document Object available for JavaScript code and demonstrates the complete tree of the object that represents the mark (figure 1 ).

Each item is a node

Obviously, the document object is 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 far, you must use Dom code for a while. For example, the code line var number = document. getelementbyid ("phone "). value; Use 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 this, the Dom is used every time you type the document into JavaScript code.

I have explained in detail the terms I have learned. The DOM tree is the tree of objects, but more specifically, it is the tree of node objects. 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 structure and use the special cases introduced in this article to practice attributes, text with elements mixed in it, and elements without text content (such as IMG elements ).

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.