If the introduced third-party JavaScript contains malicious code, the www.foo.com website will directly obtain the user logon information of www.example.com.
To solve this problem, the server can use httpOnly when setting the Cookie. The httpOnly Cookie cannot be read by JavaScript. This behavior is implemented by the browser. Mainstream browsers support the httpOnly option. To ensure security, the server always sticks to httpOnly when setting cookies.
Document. write () only outputs new content to the document
If you execute document. write after the document has been loaded, the entire HTML page will be overwritten:
Strictly speaking, the DOM Node here refers to the Element, but the DOM Node is actually a Node. in HTML, Node includes many types, such as Element, Comment, and CDATA_SECTION, and the root Node Document type. However, in most cases, we only care about the Element, that is, the Node that actually controls the page structure. ignore other types of nodes. The root node Document has been automatically bound to the global variable document.
Modifying CSS is also a frequently needed operation. The style attribute of the DOM node corresponds to all CSS and can be directly obtained or set. Because CSS allows a name such as font-size, but it is not a valid property name in JavaScript, You need to rewrite it in JavaScript to name fontSize In the hump format:
There are two ways to insert a new node. AppendChild is used to add a child node to the last child node of the parent node. For example:
In more cases, we will create a new node from scratch and insert it to the specified position:
You can create a node and add it to the DOM tree dynamically to achieve many functions. For example, the following code dynamically creates<style>
Node, and then add itAt the end of the node, a new CSS definition is added to the document dynamically:
var d = document.createElement('style');d.setAttribute('type', 'text/css');d.innerHTML = 'p { color: red }';document.getElementsByTagName('head')[0].appendChild(d);
InsertBefore
What if we want to insert the child node to the specified position? You can use parentElement. insertBefore (newElement, referenceElement); The subnode is inserted before referenceElement.
In many cases, you need to cycle all the child nodes of a parent node, which can be implemented through iteration of the children attribute:
Var I, c, list = document. getElementById ('LIST'); for (I = 0; I <list. children. length; I ++) {c = list. children [I]; // obtain the I subnode}
Delete DOM
To delete a node, first obtain the node itself and its parent node, and then call removeChild of the parent node to delete itself:
// Get the node to be deleted: var self = document. getElementById ('to-be-removed'); // obtain the parent node: var parent = self. parentElement; // Delete: var removed = parent. removeChild (self); removed = self; // true
Note that although the deleted node is not in the document tree, it is still in memory and can be added to another location at any time.
When you traverse and delete a child node of a parent node, note that the children attribute is a read-only attribute and is updated in real time when the child node changes. Therefore, when deleting multiple nodes, note that the children attribute is changing at all times.
Operation form
Using JavaScript to operate a form is similar to operating a DOM, because the form itself is also a DOM tree.
However, the input box and drop-down box of a form can receive user input. Therefore, you can use JavaScript to operate the form to obtain user input content or set new content for an input box.
The following controls are used to input HTML forms:
• Text box, corresponding <input type = "text">, used to input text;
• Password box, corresponding <input type = "password">, used to enter the password;
• Single sequence, corresponding <input type = "radio">, used to select an item;
• Check box, corresponding <input type = "checkbox">, used to select multiple items;
• The <select> drop-down box is used to select an item;
• Hide text. The corresponding <input type = "hidden"> is invisible to users, but the hidden text is sent to the server when the form is submitted.
Get value
If we obtain a reference of the <input> node, we can directly call value to obtain the corresponding user input value:
// <Input type = "text" id = "email"> var input = document. getElementById ('email '); input. value; // 'user input value'
This method can be appliedtext
,password
,hidden
Andselect
. However, for single-region and check boxes,value
The returned attribute is always the preset value of HTML, but what we need to obtain is whether the user has "checked" the option, so we should usechecked
Judgment:
// <Label> <input type = "radio" name = "weekday" id = "Monday" value = "1"> Monday </label> // <label> <input type = "radio" name = "weekday" id = "Tuesday" value = "2"> Tuesday </label> var mon = document. getElementById ('monday'); var tue = document. getElementById ('tuesday'); mon. value; // '1' tue. value; // '2' mon. checked; // true or falsetue. checked; // true or false
Set Value
The set value is similar to the obtained value. For text, password, hidden, and select, you can directly set the value:
// <Input type = "text" id = "email"> var input = document. getElementById ('email '); input. value = 'test @ example.com '; // the content of the text box has been updated.
Set checked to true or false for single-Statement and check boxes.
HTML5 controls
A large number of standard controls are added to HTML5. Commonly Used controls include date, datetime, datetime-local, and color. They all use the <input> label:
<input type="date" value="2015-07-01">
<input type="datetime-local" value="2015-07-01T02:03:04">
<input type="color" value="#ff0000">
Browsers that do not support HTML5 cannot recognize new controls and use them as type = "text" for display. HTML 5-enabled browsers can obtain formatted strings. For example, the input value of the type = "date" type is guaranteed to be a valid YYYY-MM-DD format date, or an empty string.
Submit Form
Finally, JavaScript can process form submission in two ways (AJAX is described in the following section ).
The first method is to submit a form through the submit () method of the <form> element. For example, to respond to a <button> click Event, submit the form in JavaScript code:
<Form id = "test-form"> <input type = "text" name = "test"> <button type = "button" onclick = "doSubmitForm () "> Submit </button> </form> <script> function doSubmitForm () {var form = document. getElementById ('test-form'); // you can modify the input... // submit form: form. submit () ;}</script>
The disadvantage of this method is that it disrupts the normal submission of form by the browser. Default browser click<button type="submit">
Or press enter in the last input box. Therefore, the second method is to respond<form>
Its ownonsubmit
Event, which is modified when the form is submitted:
<Form id = "test-form" onsubmit = "return checkForm () "> <input type =" text "name =" test "> <button type =" submit "> Submit </button> </form> <script> function checkForm () {var form = document. getElementById ('test-form'); // you can modify the input... // continue to the next step: return true;} </script>
Note:return true
To tell the browser to continue submitting. Ifreturn false
The browser will not continue to submit the form. In this case, the corresponding user input is usually incorrect, prompting the user to submit the form after an error message.
Check and modify<input>
Make full use<input type="hidden">
To transmit data.
For example, many login forms require the user to enter the user name and password. For security reasons, when submitting the form, the plaintext password is not transmitted, but the MD5 of the password. Common JavaScript developers directly modify<input>
:
<Form id = "login-form" method = "post" onsubmit = "return checkForm () "> <input type =" text "id =" username "name =" username "> <input type =" password "id =" password "name =" password "> <button type = "submit"> Submit </button> </form> <script> function checkForm () {var pwd = document. getElementById ('Password'); // convert the plaintext entered by the user to MD5: pwd. value = toMD5 (pwd. value); // continue to the next step: return true ;}</script>
It seems that there is no problem with this practice, but when the user enters the password for submission, the display of the password box will suddenly start from a few*
Changed to 32*
(Because MD5 has 32 characters ).
You can use<input type="hidden">
Implementation:
<Form id = "login-form" method = "post" onsubmit = "return checkForm () "> <input type =" text "id =" username "name =" username "> <input type =" password "id =" input-password "> <input type =" hidden "id =" md5-password "name =" password "> <button type =" submit "> Submit </button> </form> <script> function checkForm () {var input_pwd = document. getElementById ('input-password'); var md5_pwd = document. getElementById ('md5-password'); // convert the plaintext entered by the user to md5: md5_pwd.value = toMD5 (input_pwd.value); // proceed to the next step: return true;} </script>
Note that <input> marked name = "password" with id as md5-password, And the <input> with id as input-password does not have the name attribute. Data without the name attribute <input> will not be submitted.
Operation File
In an HTML form, the only control that can upload files is <input type = "file">.
Note: When a form contains <input type = "file">, the form's enctype must be set to multipart/form-data, and the method must be set to post, the browser can correctly encode and send the form data in multipart/form-data format.
For security reasons, the browser only allows users to click <input type = "file"> to select a local file, using JavaScript to assign values to <input type = "file"> has no effect. After you select to upload a file, JavaScript cannot obtain the actual path of the file:
Files to be uploaded:
Generally, the uploaded files are processed by the backend server. JavaScript can check the file extension when submitting the form to prevent users from uploading invalid files:
var f = document.getElementById('test-file-upload');var filename = f.value; // 'C:\fakepath\test.png'if (!filename || !(filename.endsWith('.jpg') || filename.endsWith('.png') || filename.endsWith('.gif'))) { alert('Can only upload image file.'); return false;}
File API
Because JavaScript has very limited operations on files uploaded by users, especially the file content cannot be read, many webpages requiring file operations have to be implemented using third-party plug-ins such as Flash.
With the popularity of HTML5, the new File API allows JavaScript to Read File Content and obtain more File information.
The File API of HTML5 provides two main objects: File and FileReader, which can obtain File information and read files.
The following example shows how to read the image file selected by the user and preview the image in <div>:
Image preview:
Var fileInput = document. getElementById ('test-image-file'), info = document. getElementById ('test-file-info'), preview = document. getElementById ('test-image-preview'); // listens for the change event: fileInput. addEventListener ('change', function () {// clear the background image: preview. style. backgroundImage = ''; // check whether the file is selected: if (! FileInput. value) {info. innerHTML = 'no selected file'; return;} // get File reference: var file = fileInput. files [0]; // obtain the File information: info. innerHTML = 'file: '+ file. name + '<br>' + 'size:' + file. size + '<br>' + 'modify:' + file. lastModifiedDate; if (file. type! = 'Image/jpeg '& file. type! = 'Image/png '& file. type! = 'Image/gif') {alert ('is not a valid image file! '); Return;} // read the file: var reader = new FileReader (); reader. onload = function (e) {var data = e.tar get. result; // 'data: image/jpeg; base64,/9j/4AAQSk... (base64 encoding )... 'preview. style. backgroundImage = 'url ('+ data +') ';}; // read the file in DataURL format: reader. readAsDataURL (file );});
The code above demonstrates how to read the File content through the HTML5 File API. The file read in the form of DataURL is a string, similar to data: image/jpeg; base64,/9j/4AAQSk... (base64 encoding )..., it is often used to set images. If processing is required on the server side, send the base64 character string to the server and use Base64 to decode the binary content of the original file.
Callback
The code above also demonstrates an important feature of JavaScript, namely the single-thread execution mode. In JavaScript, the browser's JavaScript execution engine always executes JavaScript code in single-threaded mode. That is to say, JavaScript code cannot be executed by more than one thread at a time.
You may ask how to handle multiple tasks for JavaScript executed in single-thread mode?
In JavaScript, multi-task execution is actually asynchronous, such as the above Code:
reader.readAsDataURL(file);
An Asynchronous Operation is initiated to read the file content. Because it is an asynchronous operation, we do not know when the operation ends in JavaScript code. Therefore, we need to set a callback function first:
Reader. onload = function (e) {// This function is automatically called after the file is read :};
After the file is read, the JavaScript engine automatically calls the callback function we set. When the callback function is executed, the file has been read, so we can safely obtain the file content within the callback function.
The above discussion about the JavaScript browser object is all the content shared by the editor. I hope you can give us a reference and support the house of helpers.