Learning from scratch _ JavaScript _ series (8) -- js series (2) (event trigger sequence, text reading, js compiling ajax, input validation, and down menu)

Source: Internet
Author: User

Learning from scratch _ JavaScript _ series (8) -- js series (2) (event trigger sequence, text reading, js compiling ajax, input validation, and down menu)

(20) event trigger sequence

If there are multiple scripts in the document (for example, automatically executed scripts), they are executed in a certain order (in the HTML document ):

① Execute first<Script> label in. Therefore, the js script here is usually embedded code, pointing to the JS file, where you can define the function to be used later;

② Second, executionScript label in;

③ The trigger script is executed, for example, The onclick = "command added on the button is triggered after the button is clicked.


(21) Document Object Model (DOM)

Document Ojbect Model allows scripts to control Web pages, windows, and documents. For JavaScript, it is a powerful tool for creating dynamic pages.

DOM is not a part of the JavaScript language, but an API (Interface) built into the browser ),

To manipulate browsers and documents, JavaScript uses hierarchical parent objects and sub-objects (tree structure), which is called DOM to represent all the content and components of a Web document.

DOM object with attributes and methods.

① The top layer is the window object, which indicates an entire browser interface. The framework can be represented by the window object. For example, alert is the method of the window object.

② The document object represents a web document or page. The web document is displayed in the browser window, so it is obvious that the document object is a sub-object of the window object;

For this reason, both Doc ument and document refer to the current window;

If multiple windows (or frames) are used, multiple window objects must be used. Each window object has its own document object. Therefore, use one of them to indicate the window name and Object Name;

(22) Obtain Document Information

① Document. Equals (do not understand, is this a string object ?);

If you want to give users a different address, use the window. location object;

② Document. title lists the titles of the current page, which are defined by the title tag in HTML.

For example:

Ti = document. title;

Alert (ti );

The effect is the output title. Note that there are no parentheses;

③ Document. referrer is the address of the last page viewed by the user at http://blog.csdn.net/qq20004604/article/details/urladdress;

④ Document. lastModified is the last modification date of the document, which is uploaded from the server to the page (Note: In the 360 browser, this time is changed, and in Firefox, this time is fixed) however, the server may run normally and verification is required;

⑤ Document. bgColor and document. fgColor are the background and foreground (TEXT) colors of the document. They correspond to the BGCOLOR and TEXT attributes under the body;

For example:

Abc

<Script>

Ti = document. bgColor;

Alert (ti );

</Script>

The output is green, and the background color turns green.

⑥ Document. linkColor, document. alinkColor, and document. vlinkColor are links in the document. Corresponds to the LINK, ALINK, and VLINK attributes in the body Tag respectively (but you do not know what these three attributes mean ).

7. document. cookie allows reading and setting a document cookie. More details.

(23) history Object

An accessible property:

History. length, the number of different addresses accessed by the user.

For example, code indicates the number of currently accessed addresses

<Script>

Alert (history. length );

</Script>

The initial value is 1. If you access another webpage, the pop-up value is 2. If you access more pages, the value increases accordingly.

Method 1:

History. go (parameter)

Open a URL in the History List. The parameter is positive or negative.

History (-1) is equivalent to a step back.

Method 2:

History. back () loads the previous URL in the history list, which is equivalent to clicking back.

Method 3:

History. forward () loads the last URL in the history list, which is equivalent to clicking the forward button.


(24) AJAX

In traditional cases, there is only one communication method between JavaScript and the server-form.

1. Front-end/webpage:Create an XMLHttpRequest object and send it to the Web server. Instead of waiting for the request, you can send the request again.

2. servers:Send the file containing the content (or the output of the server application) as the response.

3. Front-end:After receiving a response from the server, the corresponding JavaScript function is triggered to process the relevant data.

4. DOM:Because the purpose of this technology is to achieve better interaction (otherwise, the page must be refreshed when server information is received), the script uses DOM to display data from the server, so that the page does not need to be refreshed again.

Others:Multiple requests can be processed simultaneously (sending multiple requests does not affect the speed of the server ).

AJAX applications:

It is mainly used to create Web programs-user-oriented and Web-based services.

XMLHttpRequest: (the concept of pure view is quite confusing)

1. Create a request

Create an XMLHttpRequest object:

Var ajaxreq = new XMLHttpRequest ();

Note: Except for IE5/6 (ActiveX controls must be enabled in earlier versions). The syntax is different;

2. Open http://blog.csdn.net/qq20004604/article/details/URL

Ajaxreq. open ("get", "filename ");

You can use the GET or POST command (get here );

Because GET needs to send parameters to the server as the address, for example:

Ajaxreq. open ("get", "search. php? Query = abc ");

Access the search. php webpage and send abc as the query parameter to the server.

Q: Why is query?

3. Send a request

Ajaxreq. send (null );

Note: The get method uses null, and the post method uses the data sent.

4. Waiting for response:

XMLHttpRequest provides a dedicated event handler for processing the returned information of the server.

Ajaxreq. onreadystatechange = MyFunc;

A request object has a property named readyState, representing the current status of a request.

This event is triggered when the readyState attribute changes.

The change range of the ReadyState attribute value is as follows:

0 new requests;

4. Closed requests

Therefore, the event handler checks this attribute to see if its value has changed to 4.

Because an error may occur, the status is set to 200 when the request is successful. If an error occurs, the value is set to the corresponding error code.

Error-related explanation information (OK upon success) will be saved in the statusText attribute.

5. Explain the response data

When the value of the readyState attribute is 4 and the request has been responded, you can use the other two attributes to further access the returned data from the server.

ResponseTeXt is used to access the response information that exists in the original text;

ResponseXML is used to access the response information in the form of an XML object.

When the data format is not XML, only text attributes can be accessed.

Is xml a. xml file?

Such as code:

// AJAX Library

Var ajaxreq = false, ajaxCallback;

Function ajaxRequest (filename)

{

Try

{

// Firefox/IE7/Others

Ajaxreq = newXMLHttpRequest ();

}

Catch (error)

{

Try

{

Ajaxreq = newActiveXObject ("Microsoft. XMLHTTP ");

}

Catch (error)

{

Return false;

}

}

Ajaxreq. open ("GET", filename );

Ajaxreq. onreadystatechange = ajaxResponse;

Ajaxreq. send (null); // send the request

}

// Event handler

Function ajaxResponse ()

{

If (ajaxreq. readyState! = 4) return;

If (ajaxreq. status = 200)

{

// The request is successful because the event is normal.

If (ajaxCallback) ajaxCallback ();

}

Else

{

Alert ("Requestfailed" + ajaxreq. statusText );

}

Return true; // Why does return true? As long as readyState is equal to 4, it will succeed?

}

AjaxRequest () function:

All operations required to process, create, and send XMLHttpRequest objects are implemented.

This function first creates the XMLHttpRequest object. In this case, different commands are required for different browsers. If an incorrect command is used, an error will occur.

Therefore, try and catch statements are required.

First, try to use the standard method. If an error occurs, use another method (this is for IE5 and IE6). If not, return a false value to ajaxreq and use the condition to judge, tell the user that the browser does not support AJAX.

AjaxResponse () function:

The ajaxResponse () function is the onreadystatechange event handler.

This function first checks the readyState attribute to check whether the value is 4. If not, do nothing (return)

If the value is 4, check whether the attribute value is 200 (200 indicates successful). If yes, run the processing function stored in the ajaxCallback variable.

If it is not 200, it indicates an error has occurred. The alert dialog box prompts an error message.

Use the AJAX Library:

① Save the library file as ajax. js and place it in the same directory as HTML and script.

② Use <scriptsrc = "ajax. js"> to import the file to HTML.

③ Create a processing function for the request end event and set the value of the variable ajaxCallback to this function.

④ Call the ajaxRequest () function. The parameter is the file name of the server application (or file. (This database only supports GET, so you do not need to specify the POST method ).

⑤ If the request operation ends normally, the function specified in ajaxCallback will be called. At the same time, the global variable ajaxreq stores the server's response data in the responseXML and responseText attributes respectively.

Use the AJAX library to compile the AJAX quiz program:

After creating a reusable AJAX library, you can use it to create JS programs.

JS Code example;

Var qn = 0; // qn is the problem number

Function getQuestions ()

{

Qn = 0; // click Start to reset the problem.

Obj = document. getElementById ("question"); // obj is of question (HTML)

// Set the following line because it is displayed before the asynchronous loading is successful.

Obj. firstChild. nodeValue = "(pleasewait)"; // the value of the first subnode in all subnodes of obj is please wait. The role is to write it...

AjaxCallback = nextQuestion; // assign the function to the callback function (ajaxCallback), which is called in ajax

AjaxRequest ("questions. xml"); // call the ajax library to load the questions. xml file

}

// Read and output problems

Function nextQuestion ()

{

Questions = ajaxreq. responseXML. getElementsByTagName ("q"); // questions is assigned q As the tag in the XML file returned by AJAX (in XML)

Obj = document. getElementById ("question"); // The objtag is question(in ajax.html)

If (qn

{

Q = questions [qn]. firstChild. nodeValue; // q is the read value.

Obj. firstChild. nodeValue = q; // enter it in HTML.

}

Else

{

Obj. firstChild. nodeValue = "(no more questions)"; // if there are no more problems, prompt the user

}

}

Function checkAnswer ()

{

Answers = ajaxreq. responseXML. getElementsByTagName ("a"); // answers is an array (because there are multiple tags)

A = answers [qn]. firstChild. nodeValue; // The text value of the first subnode in all child nodes (childNodes)

Answerfield = document. getElementById ("answer"); // The value of the content (id is answer) of the HTML input position

If (a = answerfield. value) // if the read value (in XML) is the same as the input value (in HTML user input)

{

Alert ("Correct! "); // The prompt in the pop-up box is correct.

}

Else

{

Alert ("Incorrect. The correct answer is:" + a); // The error message is displayed in The dialog box and The correct answer is displayed.

}

Qn + = 1; // question No. + 1

Answerfield. value = ""; // reset the answer

NextQuestion (); // call a function

}

Obj = document. getElementById ("startq"); // ojb is the startq button

Obj. onclick = getQuestions; // call the function after you click it. If you do not use (), the function is not executed. The function is executed only after you click it.

Ans = document. getElementById ("submit"); // ans is the submit button.

Ans. onclick = checkAnswer; // call the function after clicking

There is also an XML file:

A

1

B

2

C

3

D

4

E

5

Finally, the html file:

AJAX Testing

<Scriptsrc = "ajax. js"> </script>

AJAX test example

<Scriptsrc = "quiz. js"> </script>

Effect:

① Click the Start the Quiz button to read the XML file and output the read problem to html.

② The answer box can be used to enter the answer and press the submit button to submit the answer.

③ Perform verification after submission. If it is consistent with the reserved answer, the prompt or incorrect prompt indicates the correct answer.

④ Then change to the next question.

(25) name

The role of name is similar to that of id.

But there are some other functions:

L Purpose 1: ID of the server that serves as an HTML element that can interact with the server, such as input, select, textarea, And button. On the server side, we can use Request. Params to obtain the value submitted by the element based on its Name.

L purpose 2: HTML element Input type = 'radio' group. We know that the radio button control is in the same group class. The check operation is mutex and only one radio can be selected at a time, this group is implemented based on the same Name attribute.

L purpose 3: Create an anchor in the page. We know that link gets a page hyperlink. If you use Name instead of the href attribute, for example, we get a page anchor.

L purpose 4: act as the Identity of an Object, such as Applet, Object, and Embed. For example, in the Applet object instance, we will use its Name to reference this object.

L purpose 5: When the IMG and MAP elements are associated, if you want to define the IMG hotspot area, you need to use its attribute usemap, make usemap = "# name" (Name of the associated MAP element ).

L Purpose 6: Attributes of certain elements, such as attribute, meta, And param. For example, defining parameters for an ObjectOr Meta .



(26) verify whether the input content is null or a number

Field is the id of the input.

Function checkIsNumber (field) // check whether the input text is a number. This field is the id value.

{

With (field)

{

If (value = null | value = "")

{

Document. getElementById (field). innerText ="Enter content";

}

Else {

If (value> 0)

{

Returnfalse;

}

Else {

Document. getElementById (field). innerText ="Enter a number";

}

}

}

Return true;

}


(27) drop-down list


If it is selected by default (that is, it is not the first one by default), add the following red section (that is, this is selected by default)

1 2 3 4



(28) differences between div, span, and ul

① Div is a block. It occupies a row and contains a line break between different Divs.

Example: fffwwwppp

The display is:

Fff

Www

Ppp

② Span is a small block in the row without line breaks.

Example: fffwwwppp

The display is: fffwwwppp

③ Ul is currently known to have built-in indentation.



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.