Review written interview distal end (4)

DOM summary

25. What is the DOM event model?

  • Bubbling and capture
  • If this element is the element that was clicked, then the capture is not necessarily before the bubble, the order is determined by the order of the listener.

26. What event delegate is what are the benefits?

Event delegates is the use of bubbling principle , to bind events to the node of the parent node , thereby triggering effect event code.

Event delegate benefits:

1) js improve performance;

2) elements added later can trigger the same event;

Code:

 var ul = document.querySelector('ul')
    ul.addEventListener('click',function(e){
        var el = e.target
        while(el.tagName !== 'LI'){
            if(el === ul){
                el = null
                break
            }
            el = el.parentNode
        }

        if(el){
            console.log('你点击了 li 元素')
        }else{
            console.log('你点击的不是 li 元素')
        }
    })

27, the mobile end of the touch event to understand it?

touchstart, touchmove, touchend, touchcancel
analog swipe events: recording position twice touchmove difference, if the right side after a previous described slide rightward.

HTTP Review:

28, HTTP caching how to do? Forced difference and contrast cache buffer.

Here Insert Picture Description
When the cache data exists, based only on the forced caching , request data flow is as follows
Here Insert Picture Description
when the cached data already exists, based only on the comparison of the cache , the data request process is as follows
Here Insert Picture Description
, we can see the different types of caching rules, forced to take effect if the cache is not necessary again and server interaction occurs, and whether or not the cache entry into force of contrast, need to interact with the server.
Two types of caching rules can exist simultaneously, forcing the cache higher priority in comparison cache, that is, when a forced cache rule, if the cache entry into force, directly using the cache, the cache is no longer performed comparing the rules.

Summary
for mandatory cache, the server tells the browser cache a time, in the buffer time, the next request, the direct use of the cache, not in time to perform the comparison caching policy.
For comparison the cache, the cache information in Etag and Last-Modified request to the server by sending, by the verification server returns a status code 304, the browser cache directly.

29. What Cookie that? Session is what?

Cookie
the HTTP response is provided by the Set-Cookie Cookie
browser to access the specified domain name is Cookie must bring Header as the Request
Cookie typically used to record user information

The Session
the Session is a server memory (data)
the Session typically achieved by recording a Cookie SessionID
SessionID generally random number

30. What is the difference LocalStorage and Cookie is?

Cookie is sent to the server with the request, but without LocalStorage
Cookie size is generally 4k or less, generally about 5Mb LocalStorage
Here Insert Picture Description

31. What is the difference between GET and POST?

1) parameters . GET parameter in the url query parameters in, POST parameters (data) on request message in the body.
2) GET parameters (url query parameters) have length restrictions, typically 1024 characters. POST parameters (data) no length limit (but actually there are 4 ~ 10Mb limit)
3) package . GET request need only send a packet , POST requests need to send two or more packets (because there POST message body) (nonsense, GET message body may be used)
. 4) GET is used to read data , POST is used to write data , POST no power etc. (idempotent, which means that no matter how many times the request is sent, the results are the same.)
5) security. GET POST is not secure (not safe)
specific HTTP brief description, see link

32, how cross-domain? What JSONP, what CORS, what postMessage Yes.

JSONP (JSON with Padding) is a data format JSON "use mode" that allows web pages to data from other domains.

By way of script tag to load data to obtain data as JS code to perform a function declaration in advance on the page, the function name passed back by way of parameter passing interface backstage after the function name resolves to "wrap" on the raw data function name, sent to the front. In other words, JSONP needs to correspond with back-end interfaces can be achieved.

JSONP text flow

JSONP requester: sending a request to the browser

JSONP responder: the server is sent a request

1, the requesting party to create script, src responder point, while passing on the side of the channel response and query parameters script src = '/路径?callback =' + functionName

2, the responder according to the callback query parameters, such as shape constructed ${query.callback}.call(undefined,'你要的数据'), such response

3, the browser receives the response will be executed ${query.callback}.call(undefined,'你要的数据')

4, the requesting party will know the data he wants

Convention:
functionName is the name of a function, and the name is randomly generated, the form

var functionName = 'keduoc' + parseInt(Math.random()*100000,10)   // keduoc23238
window[functionName] = function(response){
      if(response === '你要的数据'){
      ......
      }
}

JSONP of jQuery way:

$.ajax({
        url:"/路径",              // 不传查询参数是因为jQuery会自动生成并添加
        dataType:"jsonp",         // 记得每行结尾的逗号
        success: function(response){
           if(response === '你要的数据'){
              ......(函数)
           }
        }
 })

In addition:

1) JSONP appear before Ajax, the main purpose is to solve the interactive without refreshing the page and the back end.
2) The main method is to create through dynamic JSONP

Access-Control-Allow-Origin

This field is required. Its value is either the value of the specific request of the Origin field, either a *, any request for acceptance of the domain name.

Code portion
requester integrally Code

<!DOCTYPE html>
<html lang="en">
<head>
    <title>首页</title>
    <link rel = "stylesheet" href = "/style.css">
    <meta charset="UTF-8">
</head>
<body>

<h5>您的账户余额是  <span id = "amount">&&&amount&&&</span></h5>
<button id="button">打钱</button>

<script >
    button.addEventListener('click',(e) =>{
        let script = document.createElement('script');
        let functionName = 'keduo' + parseInt(Math.random()*100000,10)
        window[functionName] = function (response) {
            if (response === '你要的数据') {
                amount.innerText = amount.innerText - 1
            }
        }
        script.src = '/pay?callback='+functionName   // 注意要加上查询参数 ?callback=functionName 且注意是'...' + functionName
        document.body.appendChild(script)
        script.onload = function (e) {
            e.currentTarget.remove()
            delete window[functionName]
        }
        script.onerror = function (e) {
            e.currentTarget.remove()
            delete window[functionName]
        }
    })

</script>
</body>
</html>

Requester overall code may be simplified to jQuery

<!DOCTYPE html>
<html lang="en">
<head>
    <title>首页</title>
    <link rel = "stylesheet" href = "/style.css">
    <meta charset="UTF-8">
</head>
<body>

<h5>您的账户余额是  <span id = "amount">&&&amount&&&</span></h5>
<button id="button">打钱</button>

<script >
    button.addEventListener('click',(e) =>{
      $.ajax({
        url:"/路径",              // 不传查询参数是因为jQuery会自动生成并添加
        dataType:"jsonp",         // 记得逗号
        success: function(response){
           if(response === '你要的数据'){
              amount.innerText = amount.innerText - 1
           }
        }
       })
    })

</script>
</body>
</html>

Code overall responder

var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?\nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('方方说:含查询字符串的路径\n' + pathWithQuery)

  if(path === '/'){
    var string = fs.readFileSync('./index.html','utf8')
    var amount = fs.readFileSync('./db','utf8')
    string = string.replace('&&&amount&&&',amount)   //将数据库中的数据代替占位符
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(string)
    response.end()
  }else if(path ==='/style.css'){
    var string = fs.readFileSync('./style.css','utf8')
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(string)
    response.end() 
  }else if(path === '/main.js'){
    var string = fs.readFileSync('./main.js','utf8')
    response.setHeader('Content-Type','application/javascript')
    response.write(string)
    response.end()
  }else if(path === '/pay'){
    var amount = fs.readFileSync('./db','utf8')
    var newAmount = amount - 1
    fs.writeFileSync('./db',newAmount)
    response.setHeader('Content-Type','application/javascript')
    response.write(`${query.callback}.call(undefined,'你要的数据')`)
    response.end()
  }else{
    response.statusCode = 404
    response.setHeader('Content-Type','text/html;chatset=utf-8')
    response.write('找不到对应的路径,你需要自行修改 index.js')
    response.end()
  }
  })
Released four original articles · won praise 0 · Views 86

Guess you like

Origin blog.csdn.net/weixin_43915673/article/details/104736825