[CyberSecurityLearning 50] JS basics + functions + objects + events

table of Contents

Introduction to JavaScript:

JS

Simple sentence

How to introduce JS code in HTML

variable

Declare variable

Variable type

null和undefined

Array

Object

Process control

if statement judgment

for loop

for ... in

while loop

do while

function

Object

Browser built-in objects:

window represents the browser globally

screen

location

document is very important

document.cookie (important)

Manipulate the DOM

DOM node

The most common way to get DOM nodes

event

1. Judge whether the password entered twice is consistent with JS implementation

achieve:

test:

2. Expansion: Use JS AJAX technology to judge whether the user name is unique when registering

AJAX

achieve:

test


 

Introduction to JavaScript:

JavaScript ("JS" for short) is a lightweight, interpreted or just-in-time compiled programming language with function first. Although it is famous as a scripting language for developing Web pages, it is also used in many non-browser environments. JavaScript is based on prototype programming, a multi-paradigm dynamic scripting language, and supports object-oriented, imperative and declarative ( Such as functional programming) style.

JavaScript was first designed and implemented on Netscape Navigator browser by Brendan Eich of Netscape in 1995. Because Netscape cooperated with Sun, Netscape management wanted it to look like Java, so it was named JavaScript. But in fact, its grammatical style is closer to Self and Scheme.

The JavaScript standard is ECMAScript. As of 2012, all browsers fully support ECMAScript 5.1, and older browsers support at least the ECMAScript 3 standard. On June 17, 2015, ECMA International released the sixth edition of ECMAScript. The official name is ECMAScript 2015, but it is usually called ECMAScript 6 or ES6.

JS

The operating environment of JS is a browser

JS can do things only you can't think of, nothing it can't do

(Chrome browser industry standard )

Front-end security

Interpreted language
Every time the page is refreshed, the JS code will be executed
sequentially from top to bottom.
When we directly access the JS script, the plain text content is returned.
JS is case sensitive

Quick start

JS can be mixed with HTML and
can appear anywhere in HTML

Simple sentence

Output statement

alert(); //pop up

console.log(); //output in the console

How to introduce JS code in HTML

内部JS:<script></script>

<script src=“./js/test1.js”></script>
<script src=“http://localhost/JS/js/test1.js”></script>
<script src=“http://172.168.23.63/JS/js/test1.js”></script> 

Js script can be introduced from the outside 
<Script 
type = "text / JavaScript" the src = "vendors.47ee6caee3579c652820.js" 
Integrity = "SHA512-D2n5DNLLXR1Pg0RECW6VRkt2hStlq9lyb52AiW1vAXQbklC0SFw0wBvQ9K2lldtGDWyit3AakyxPWHdXieKQIQ ==" 
the crossOrigin = "Anonymous"> </ Script>

外部JS:type="text/javascript"

variable

Declare variable

var is strongly recommended to declare.
Note that you can only use var to declare once (the same variable can be assigned repeatedly)

var name = "Waffle";
var a = 1;

Variable type

Number
can do four arithmetic

String and boolean

null和undefined

Null represents an "empty" value, which is different from 0 and the empty string "0 is a numeric value," represents a string with a length of 0, and null represents "empty"

In other languages, there is also a representation of null similar to Javascript. For example, Java also uses null, Swift uses nil, and Python uses None.

However, in Javascript, there is another undefined similar to null, which means "undefined"

The designers of Javascript wanted to use null to indicate an empty value, and underfined to indicate that the value was undefined. Facts have proved that this is useless, and it makes little sense to distinguish between the two. In most cases, we should use null. undefined is only useful in judging whether the function parameters are passed.

Array

The array can contain any data type
var arr = [1,2,3.14,"GGG"]
call the array
arr[0]

Object

JavaScript objects are a set of unordered collections composed of key-values.
Use square brackets when defining arrays, and use curly brackets when defining objects.

var person = {
    name : 'Bob',
    age: 20,
    tags:['js','web'],
    city:'beijing',
    hasCar:true
}

Call object

person.name

Process control

if statement judgment

var age = 15;
if (age >= 18){
    alert('adult');
}else{
    alert('teenager');
}

for loop

var x = 0;
var i;
for(i=1; i<=10000; i++){
    x = x + i;
}
x;//50005000

for ... in

var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var key in o) {
    console.log(key); 
}
//'name', 'age', 'city'

 

while loop

var x = 0;
var n = 99;
while (n > 0) {
    x = x + n;
    n = n - 2;
}
x;//2500

do while

var n = 0;
do {
    n = n + 1;
}while (n < 100);
n;//100

function

The benefits of defining functions are easy to call

The definition function function abs(){} abs is to calculate the absolute value of a number

Call function abs(-1);

 

Object

Navigate the browser through objects

Browser built-in objects

Browser built-in objects:

window represents the browser globally

Generally, you will omit the window and write directly. The window is equivalent to the root of the domain name, which can be omitted by default

To access the properties in the object, you need to use some points.

Browser related information

Firefox is owned by Netscape

screen

Screen information

location

Get the url information of the current page

document is very important

Represents the current interface

document.cookie (important)

Can complete the reading and writing of cookie information

alert(document.cookie);

document.cookie="name=hello";

test:

After refresh

Username is directly modified


Document Object Model (DOM)

Manipulate the DOM

DOM node

Since the HTML document is a DOM tree after being parsed by the browser, to change the structure of HTML, you need to manipulate the DOM through Javascript

operating:

    Update: Update the content of the DOM node, which is equivalent to updating the HTML content represented by the DOM node

    Traverse: Traverse the newly added child nodes under the DOM node for further operations

    Add: Add a child node under the DOM node, which is equivalent to dynamically adding an HTML node

    Delete: Delete the node from the HTML, which is equivalent to deleting the content of the DOM node and all the subsections it contains

 Before operating a DOM node, we need to get the DOM node in various ways
 

The most common way to get DOM nodes

document.getElementById()

document.getElementsByTagName()

document.getElementsByClassName() //CSS selector

Since the ID is unique in the HTML document, document.getElementById() can directly locate the only DOM node document.getElementsByTagName() and document.getElementsByClassName() return a group of DOM nodes. To accurately select the DOM, you can locate it first The parent node, then select from the parent node to narrow the scope.

//Return the node whose ID is'test':

var teest = document.getElementById ('test') ;

//First locate the node whose ID is'test-table', and then return all tr ​​nodes within it:

var trs = document.getElementById('test-table').document.getElementsByTagName('tr');

//First locate the node whose ID is'test-div', and then return the red nodes contained in all classes within it:

var reds = document.getElementById('test-div').document.getElementsByClassName('red');

//Get all the direct child nodes under the node'test':

var cs = test.children;

//Get the first and second child nodes under node test:

var first = test.firstElementChild;

var last = test.lastElementChile;

The second method

To use querySelector() and querySelectAll(), you need to understand the select syntax, and then use conditions to get nodes, which is more convenient

    //Get the node with ID q1 through querySelector:

    var q1 = document.querySelector('#q1');

    //Get all eligible nodes in the q1 node through querySelectorAll:

    var ps = q1.querySelectorAll('div.highlighted > p');

    Note: The lower version of IE<8 does not support querySelector and querySelectorAll. IE8 only supports limited

Strictly speaking, our DOM node here refers to Element, but DOM node is actually Node. In HTML, Node includes Element, Comment, CDATA_SECTION, etc., as well as the root node Document type, but most of the time we only Care about Element, which is the Node that actually controls the structure of the page, and ignore other types of Node. The root node Document has been automatically bound to the global variable document.

 

event

User trigger event

Mouse event

     Such as onclick (mouse click), dbclick (mouse double click), etc.

Keyboard events

form event

Incident response

1. Judge whether the password entered twice is consistent with JS implementation

achieve:

<script>
function fm(){     var ps1=document.getElementById('pas1');     var ps2=document.getElementById('pas2');     if(ps1.value != ps2.value){         alert("Twice password The input is inconsistent, please re-enter");         ps1.value="";         ps2.value="";     } } </script>









 

Create another response event

<input type="submit" οnmοuseοver="fm()" name="userSubmit" value="注册">

<html>
<head>
	<meta charset="utf-8">
	<title>注册--刹那芳华</title>
</head>
<body>
	<h1>刹那芳华BBS 论坛</h1>
<form
	action="./addUser.php"
	method="POST"
>
用户名:<input id="user" type="text" name="userName"><br />
密码:<input id="pas1" type="password" name="userPass1"><br />
确认密码:<input id="pas2" type="password" name="userPass2"><br />
<script>
function fm(){
	var ps1=document.getElementById('pas1');
	var ps2=document.getElementById('pas2');
	if(ps1.value != ps2.value){
		alert("两次密码输入不一致,请重新输入");
		ps1.value="";
		ps2.value="";
	}
}
</script>
<input type="submit" onmouseover="fm()" name="userSubmit" value="注册">
 
</form>
	<hr />
</body>
</html>

After entering the password, when our mouse cursor moves to the registration button,

A mouse response event will occur, and JS will execute to determine whether the two entered passwords are consistent

If they are inconsistent, a box will pop up to remind the user that the password is incorrectly entered twice and clear it.

test:

2. Expansion: Use JS AJAX technology to judge whether the user name is unique when registering

AJAX

xmlhttp=new XMLHttpRequest(); Create an XMLHttpRequest object 

Send a request to the server:

xmlhttp.open("GET","./getUserName.php?q="+str,true); 
xmlhttp.send();

responseText to obtain the response data in the form of a string

achieve:

Server-side response file:

getUserName.php

<?php
include "../inc/dblink.inc.php";
?>
<?php
$sql = "SELECT * FROM `users`";
if($results = mysqli_query($link,$sql)){
	while($result=mysqli_fetch_assoc($results)){
		$a[]=$result['name'];
	}
}else{
	mysqli_error($link);
}
 
$q=$_GET["q"];
if (strlen($q) > 0)
{
  $hint="";
  for($i=0; $i<count($a); $i++)
  {
	if($q === $a[$i]){
		$hint=$a[$i];
		break;
	}
  }
}
 echo $hint;
?>
<?php
mysqli_close($link);
?>

Create a response event onmouseout, when the user's mouse leaves the input box, trigger the response event, call the following JS, send a get request to the server's ./getUserName.php and pass in the string entered by the user

The server (getUserName.php) extracts all user names from the database, compares it with the incoming string, and returns a comparison result. The following JS processes the information returned by the server, and then gets a response on the user interface.
 

<script>
function showHint(str)
{
  var xmlhttp;
  if (str.length==0)
  {
    document.getElementById("user").innerHTML="";
    return;
  }
    xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
         if(xmlhttp.responseText){
            alert("用户名已存在,请重新输入!");
            
        }
      //document.getElementById("user").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","./getUserName.php?q="+str,true);
  xmlhttp.send();
}
</script>
 

register.php

<html>
<head>
	<meta charset="utf-8">
	<title>注册--刹那芳华</title>
</head>
<body>
	<h1>刹那芳华BBS 论坛</h1>
<form
	action="./addUser.php"
	method="POST"
>
<script>
function showHint(str)
{
  var xmlhttp;
  if (str.length==0)
  { 
    document.getElementById("user").innerHTML="";
    return;
  }
    xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
		 if(xmlhttp.responseText){
			alert("用户名已存在,请重新输入!");
			
		}
      //document.getElementById("user").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","./getUserName.php?q="+str,true);
  xmlhttp.send();
}
</script>
用户名:<input id="user" type="text" name="userName" onkeyup="showHint(this.value)"><br />
密码:<input id="pas1" type="password" name="userPass1"><br />
确认密码:<input id="pas2" type="password" name="userPass2"><br />
<script>
function fm(){
	ps1=document.getElementById('pas1');
	ps2=document.getElementById('pas2');
	if(ps1.value != ps2.value){
		alert("两次密码输入不一致,请重新输入");
		ps1.value="";
		ps2.value="";
	}
}
</script>
<input type="submit" onmouseover="fm()" name="userSubmit" value="注册">
 
</form>
	<hr />
</body>
</html>

test

First, we enter the database to view the users table, we can see that there are two users [GGG, test]

 

Enter a user name that already exists in the GGG database, an error will be reported

 

Enter a user name that does not exist in the database, normal

Both response events can work normally

registration success

test was successful

For details, please see: https://blog.csdn.net/weixin_43252204/article/details/105717411

Guess you like

Origin blog.csdn.net/Waffle666/article/details/115049174