web123456

AJAX JS DOM front and back interactions Detailed steps hand in hand (graphic)

Front- and back-office interaction steps

I. Build the background

1. Create the project directory basepro

2. Create a static folder in the project directory public

3. Installation of dependencies

First of all this generates apackage.json configuration file and add the appropriate version information in it, so that when you run the program later, the installation dependency package can be directlynpm install xxx

Next, install npm installexpressThe node_modules directory is created in the project directory and all dependent packages are added to that directory.

4. Create the entry file that serves as the project's entry point for the creation of application objects

- Introduction of express

- Creating a WEB server

- Listening on port 8080

- Hosting static resources . /public file

- Create a route for a get method request and look at the parameters and give the return value

- Parses the form's data in url-encoded format.

- Creates a route for post requests and looks at the parameters and gives a return value.

- Create a route for a put method request and look at the parameters and give the return value

- Create a route for delet mode requests and look at the parameters and give the return value

5. Operation

  1. // Type npm install express in a terminal in the current directory to install the
  2. //1. Introducing express
  3. var express = require('express');
  4. //2. Create the web server, instantiate it
  5. var app = express();
  6. //3. Setting the port
  7. app.listen(8080);
  8. /* 4. Static Resource Managed() takes the static resource's
  9. directory into the parameter, it is not necessary to have only this one file directory to host, the
  10. It's not the only directory where you can */
  11. app.use(express.static('./public'));
  12. //5. Start the server node in the terminal
  13. / / 6. to the foreground an interface address, because the foreground send request with the get, background interactive data, also with the get
  14. //address path (string format)
  15. //Receive foreground? mode passed parameters
  16. app.get('/getpar1',(req,res)=>{
  17. console.log(req.query)
  18. })
  19. // The address of the interface that receives the post method
  20. The format passed via urlencoded needs to be parsed separately before //receiving it
  21. app.use(express.urlencoded({extended:false}))
  22. app.post('/ajaxpost',(req,res)=>{
  23. console.log(req.body)
  24. res.send('post method return value')
  25. })
  26. // Receive the interface address of the put method
  27. app.put('/ajaxput',(req,res)=>{
  28. console.log(req.body);
  29. res.send('put method return value');
  30. })
  31. // Receive the interface address of the delete method.
  32. app.delete('/ajaxdel/:names',(req,res)=>{
  33. console.log(req.params);
  34. res.send('delete method return value')
  35. })

II. Browser requests

way (of life)

  1. <script>
  2. //1. Create xhr object
  3. var xhr = new XMLHttpRequest();
  4. //4. Originally received data, now by listening to determine the value of readyState, for 4 when the receipt came back
  5. xhr.onreadystatechange = function () {
  6. //()
  7. //Determine if readyState is 4 before you can get the backend data.
  8. if (xhr.readyState == 4) {
  9. //Determine the success of the return content, and then receive data
  10. if (xhr.status >= 200 && xhr.status < 300) {
  11. var result = xhr.responseText;
  12. console.log(result);
  13. }
  14. }
  15. }
  16. // 2. Setting up request information
  17. xhr.open('get','/getpar1?names=Zhang San & pwd=123456',true);
  18. //3. Send a request (the format of sending a request varies from method to method)
  19. //get method is directly () parameter can be omitted, also (null)
  20. xhr.send();
  21. </script>

way (of life)

  1. //1. Create asynchronous objects
  2. var xhr =new XMLHttpRequest();
  3. //4. Listening and returning values
  4. xhr.onreadystatechange=function(){
  5. //Judge readyState==4
  6. if(xhr.readyState ==4){
  7. //Judgment status code
  8. if(xhr.status>=200 && xhr.status<300){
  9. //Receive the return content
  10. var result=xhr.responseText;
  11. console.log(result);
  12. }
  13. }
  14. }
  15. //2. Setting up request information
  16. xhr.open('post','/ajaxpost',true);
  17. The data format of the passed parameters must be specified before sending in //post mode.
  18. //Set the request header to specify how the request parameters are parsed before passing the data.
  19. xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  20. //3. Send request
  21. xhr.send('names=bob & pwd=333');
  22. // Browser access to http://localhost:8080/

way (of life)

  1. var a='tom';
  2. var b='lili';
  3. //1. Create asynchronous objects
  4. var xhr=new XMLHttpRequest();
  5. //4. Listening for return values
  6. xhr.onreadystatechange=function(){
  7. //Judgment
  8. if(xhr.readyState==4){
  9. if(xhr.status>=200 && xhr.status<300){
  10. //Receive the return content
  11. var result=xhr.responseText;
  12. console.log(result);
  13. }
  14. }
  15. }
  16. //2. Setting up request information
  17. xhr.open('put','/ajaxput',true);
  18. // Request header
  19. xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
  20. //3. Send request
  21. xhr.send(`names=${b} & oldname=${a}`);

 way (of life)

  1. var username='Wang Wu';
  2. //1. Create asynchronous objects
  3. var xhr=new XMLHttpRequest();
  4. //4. Listening and returning values
  5. xhr.onreadystatechange=function(){
  6. if(xhr.readyState==4){
  7. if(xhr.status>=200 & xhr.status<300){
  8. var result=xhr.responseText;
  9. console.log(result);
  10. }
  11. }
  12. }
  13. //2. Setting up request information
  14. xhr.open('delete',`/ajaxdel/${username}`,true);
  15. //3. Send request
  16. xhr.send();

4. Avoid icon mistakes

<link rel="shortcut icon" href="#" />

III. DOM

brief description

DOM full name Document Object Model, that is, the documentobject modelIt allows scripts (js) to control Web pages, windows, and documents.

In a nutshell.Use js to dynamically manipulateAll elements within the browser window.

2. DOM Basic Functions

- Query an element

- Query the ancestor, brother, and descendant elements of an element

- Getting and modifying attributes of an element

- Getting and modifying the content of an element

- Creating, inserting and deleting elements

Simply put, it's the addition, deletion, and alteration of page elements.

II. Manipulation of elements (application section)

1. Get the element by its id.

`()`Write the id name of the element parameter lookup by id attribute in the document.

```js

//Get the whole of the html element whose id is called myDiv.

var myDiv = ('myDiv');

In browsers that can support ES6, you can get the element object in a shorthand way. The id value is used directly to refer to the current element object.

2. Events - interacting with elements

It is possible to bind `onclick, onmouseover, onmouseout, onmousedown, onmouseup, ondblclick, onkeydown, onkeyup`, etc. to DOM elements.JavaScript Ability to execute on an event as it occurs.

(1) Bind events directly in DOM

Setting event properties and binding methods directly in the tag completes the interaction.

html:

  1. <input type="button" value="Click me." onclick="hello(1)" />
  2. <script>
  3. function hello(a) {
  4. alert('hello world!');
  5. }
  6. </script>

(2) Binding Events in JavaScript Code

You can fetch an element via js, bind events related to the fetched element in js, and call thefunction (math.)Handle event functions.

js:

  1. var btn = document.getElementById('mybtn');
  2. btn.onclick = function () {
  3. alert('hello');
  4. };

3. Get/Set the content of the element innerHTML

Gets/Sets the content of the element.

innerHTML is a two-way function in JS: getting the content of an object or inserting content into an object.

html:

  1. <div id="myDiv">div element</div>
  2. <script>
  3. var myDiv = document.getElementById('myDiv');
  4. myDiv.innerHTML = '<p> an element </p>';
  5. </script>

- This can be achieved by `("myDiv").innerHTML` to get the inline content of the object whose `id` is `myDiv`;

-It is also possible to insert content to an object, such as `("myDiv").innerHTML='This is the inserted content';` This inserts content into the object with id myDiv.

4. Getting the value

The value attribute of an element can be used to directly retrieve the value of an element that has a value attribute. It is used in most cases to retrieve form-related elements.

html:

  1. <input type="text" id="nn" />
  2. <input type="button" value="Get." οnclick="print()" />
  3. <script>
  4. var a = document.getElementById('nn');
  5. // Getting values through events
  6. function print() {alert(a.value);}
  7. </script>

Exercise: fine-tuning

> put a text input box, a password input box, and a button on the page

> Get two input box elements and a button element using js

> Clicking on the button element triggers the click event, which gets the contents of the text input box and the password input box, and is viewed in the console.

> create two p tags, use js to get two p elements

> Display the user name and password entered by the user on the page.

01_get.html code:

  1. <body>
  2. Users:<input type="text" id="uname"><br>
  3. Password:<input type="text" id="upwd"><br>
  4. <button onclick="ajax()">log in</button>
  5. <script>
  6. ajax();
  7. function ajax() {
  8. //1. Create xhr object
  9. var xhr = new XMLHttpRequest();
  10. //4. Originally received data, now by listening to determine the value of readyState, for 4 when the receipt came back
  11. xhr.onreadystatechange = function () {
  12. //()
  13. //Determine if readyState is 4 before you can get the backend data.
  14. if (xhr.readyState == 4) {
  15. //Determine the success of the return content, and then receive data
  16. if (xhr.status >= 200 && xhr.status < 300) {
  17. var result = xhr.responseText;
  18. console.log(result);
  19. }
  20. }
  21. }
  22. var myname=uname.value;
  23. var mypwd=upwd.value;
  24. // 2. Setting up request information
  25. xhr.open('get','/getpar1?names='+myname+'&pwd='+mypwd,true);
  26. //3. Send a request (the format of sending a request varies from method to method)
  27. //get method is directly () parameter can be omitted, also (null)
  28. xhr.send();
  29. }
  30. </script>
  31. </body>

 Code:

  1. // Type npm install express in a terminal in the current directory to install the
  2. //1. Introducing express
  3. var express = require('express');
  4. //2. Create the web server, instantiate it
  5. var app = express();
  6. //3. Setting the port
  7. app.listen(8080);
  8. /* 4. Static Resource Managed() takes the static resource's
  9. directory into the parameter, it is not necessary to have only this one file directory to host, the
  10. It's not the only directory where you can */
  11. app.use(express.static('./public'));
  12. //5. Start the server node in the terminal
  13. //Receive foreground? mode passed parameters
  14. app.get('/getpar1',(req,res)=>{
  15. console.log(req.query)
  16. })

 

 Enter 127.0.0.1:8080/01_get.html in the browser, enter the user password information, and click Login.

 

The backend gets the data:

5. Clearing of extra spaces - trim() method

- The `trim()` method is used to remove the "first and last" blank characters of a string, including: spaces, tabs, newlines and other blank characters.

- The `trim()` method does not change the original string.

- The `trim()` method does not apply to null, undefined, Number types.

  1. var str = '  hello   ';
  2. alert(str.trim());

Methods for non-empty validation

  1. var str1 = '   ';
  2. var str2 = ''
  3. var str3 = ' tom ';
  4. function notEmpty(s){
  5. var nstr = s.trim();
  6.    return nstr.length;
  7. }
  8. notEmpty(str1)
  9. notEmpty(str2)
  10. notEmpty(str3)
'
(of a computer) run