Front-end Architect 01_JavaScript_Ajax

1 Web Basics

1.1 Web server

  • Web servers, also known as website servers, are mainly used to provide online information browsing services.
  • Common web server software includes Apache HTTP Server (Apache for short), Nginx, etc.

Browser and server interaction

  • In a Web server, requested resources are divided into static resources and dynamic resources.
  • Characteristics of static resources: As long as the server does not modify these files, the client will receive the same content every time it requests it.
  • The characteristic of dynamic resources is that the content can change dynamically, and each request requires calculation and processing.

What are the commonly used technologies for server-side web development? PHP, Java, ASP.NET, node.js

1.2 HTTP protocol

  • HTTP (HyperText Transfer Protocol) stands for Hypertext Transfer Protocol.
  • Used to standardize data exchange between client and server in a specified format.

HTTP is a protocol based on "request" and "response".

When the client establishes a connection with the server:

  • The client (browser) sends a request to the server, which is called an HTTP request.
  • The server responds after receiving the request, which is called an HTTP response.

How to view HTTP messages? Use your browser's developer tools. Steps:

  • ① Open the developer tools.
  • ② Switch to the Network option.
  • ③ Refresh the web page.

HTTP protocol

  • General represents basic information.
  • Response Headers represent response headers.
  • Request Headers represent request headers.
  • Click view source on the right side of Response Headers or Request Headers to view the source format of the message header.
1.2.1 Request message
  • request line
  • Request header
  • entity content
// 请求行
// GET / HTTP/1.1
// 请求头
// Host: www.itheima.com
// Connection: keep-alive	
// User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML,…
// Upgrade-Insecure-Requests: 1
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/ …
// Accept-Encoding: gzip, deflate
// Accept-Language: zh-CN,zh;q=0.9

// 请求行
// POST /form.php HTTP/1.1
// 请求头
// Host: localhost
// Content-Type: application/x-www-form-urlencoded
// Content-Length: 20
// 请求实体
// user=Jim&pass=123456

The composition of the request line

  • Request method: There are many types. For example, GET is the default method used by browsers to open web pages. Other commonly used methods are POST.
  • Requested resource path: refers to the part of the URL address that includes parameters to the right of the domain name, such as "/admin/save.php?id=1".
  • HTTP version: such as HTTP/1.1, HTTP/1.0

Note: Use spaces to separate each component of the request line.

Request header

  • The role of the request header: The request header is located after the request line and is mainly used to deliver additional messages to the server.
  • The composition of request headers: They are composed of header field names and corresponding values, separated by colons ":" and spaces.
  • Examples: data types, compression methods, languages, and system environments accepted by the browser.

entity content

  • Content encoding: described using the request header Content-Type. The encoding format <form>is set according to the enctype attribute of the tag. The default value is application/x-www-form-urlencoded. File upload is multipart/form-data.
  • Memory length: described using the request header Content-Length.
1.2.2 Response message
  • response status line
  • Response header
  • entity content
// 响应状态行
// HTTP/1.1 200 OK
// 响应头
// Date: Thu, 02 Nov 2017 06:22:27 GMT
// Server: Apache/2.4.23 (Win64) OpenSSL/1.0.2h PHP/5.6.28
// Accept-Ranges: bytes
// Content-Type: text/html

// 实体内容
// <!DOCTYPE html>
// <html><body></body></html>

response status line

  • HTTP version: For example, HTTP/1.1.
  • Status code: For example, 200.
  • Description information: such as OK.

The response status line is used to inform the client of the status of this response.

status code meaning status code meaning
200 normal 403 prohibit
301 move permanently 404 not found
302 temporary move 500 Internal Server Error
304 Unmodified 502 Invalid gateway
401 unauthorized 504 Gateway timeout

The status code represents the server's various processing results and status of the client's request.

The response header is used to inform the client of the basic information of this response, including the server program name, content encoding format, cache control, etc.

Request headers and response headers are important information for the interaction between the browser and the server. They are automatically processed by the program and usually do not require human intervention.

entity content

  • Web->Pictures
  • The server's response entity content has multiple encoding formats.
  • In order to inform the browser of the content type, the server will describe it through the Content-Type field in the response message header.
  • For example, the type of a web page is usually "text/html", which is a MIME type representation.

MIME is a common format used by most Internet applications today. The representation method of MIME is "large category/specific type".

MIME meaning MIME meaning
text/plain Normal text (.txt) image/gif GIF image (.gif)
text/xml XML text (.xml) image/png PNG image (.png)
text/html HTML text (.html) image/jpeg JPEG image (.jpeg)
text/css CSS text (.css) application/javascript JavaScript program (.js)

Browsers will handle different MIME types according to the server response.

  • Display directly when encountering ordinary text.
  • When HTML is encountered, it is rendered into a web page.
  • Displayed as images when encountering GIF, PNG, JPEG and other types.

If the browser encounters an unrecognized type, it will download the file by default.

2 Web server setup

2.1 Front-end and back-end interaction

  • Web development is divided into front-end and back-end.
  • The front end is the user-facing end, that is, browser program development.
  • The back-end provides services for the front-end, that is, server-side program development.
  • In a dynamic website, many functions are implemented by front-end and back-end interactions. For example, user registration and login, posting comments, checking points, balance, etc.
  • These operations can be divided into two categories, one is submitting data to the server (form interaction), and the other is querying data from the server (URL parameter interaction).

form interaction

Form interaction refers to creating a form in HTML. The user fills in the form and submits it to the server. The server returns the processing result after receiving the form.

URL parameter interaction

URL parameters are often used by the browser to submit some request information to the server.

3 Getting Started with Ajax

3.1 What is Ajax

Ajax: Asynchronous JavaScript And XML, asynchronous JavaScript and XML technology.

Description: It is not a new language or technology. It is a browser-side technology composed of JavaScript, XML, DOM, CSS and other existing technologies.

Function: Used to implement asynchronous interaction with the server.

The differences between Ajax and traditional web application development:

  • Traditional web workflow

  • Ajax workflow

Compared with traditional web pages, the advantages of using Ajax technology include the following aspects.

  • Reduce the load on the server
  • Save bandwidth
  • Better user experience

3.2 Create Ajax objects

Create Ajax object

  • W3C standards

    var xhr = new XMLHttpRequest();
    
  • Early IE browser

    var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    var xhr = new ActiveXObject('Msxml2.XMLHTTP');
    var xhr = new ActiveXObject('Msxml2.XMLHTTP.3.0');
    var xhr = new ActiveXObject('Msxml2.XMLHTTP.5.0');
    var xhr = new ActiveXObject('Msxml2.XMLHTTP.6.0');
    

3.3 Ajax sends request to server

  • Create a new HTTP: open() method

    • open('method', 'URL' [, asyncFlag [, 'userName' [, 'password']]])
      
    • method: used to specify the request method, such as GET, POST, case-insensitive.

    • URL: Represents the requested address.

    • asyncFlag: optional parameter, used to specify the request method, false for synchronous request, and true for asynchronous request by default.

    • userName and password: Optional parameters, indicating the user name and password for HTTP authentication.

  • Set HTTP request header: setRequestHeader() method

    • setRequestHeader('haeder', 'value')
      
    • The parameters are all of string type.

    • header represents the request header field.

    • value is the value of the field.

    • This method must be called after the open() method.

  • Send a request to the web server and receive a response: send() method

    • send(content)
      
    • content: used to specify the data to be sent. Its value can be an instance of a DOM object, an input stream, or a string. It is generally used in conjunction with the POST request type.

    • Note: If the request is declared synchronous, this method will wait for the request to complete or time out before returning, otherwise this method will return immediately.

When developing Ajax, GET or POST methods are often used to send requests.

  • The GET method is suitable for obtaining data from the server.
  • The POST method is suitable for sending data to the server. You need to set the encoding format of the content and tell the server what format to use to parse the data.

Ajax object method to send requests.

// GET
var xhr = new XMLHttpRequest();         // 创建Ajax对象
xhr.open('GET', 'test?a=1&b=2');    // 建立HTTP请求
xhr.send();

// POST
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test?a=1&b=2');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('c=3&d=4');

Synchronous requests and asynchronous requests

The third parameter of the Ajax object open() method is used to set synchronous requests and asynchronous requests. The difference between the two methods is whether to block the execution of the code .

  • Asynchronous mode (default): It is non-blocking. The browser-side JavaScript program does not need to wait for the web server to respond and can continue to process other things. After the server responds, process the response result obtained by the Ajax object.

  • Synchronous mode: It is blocking. When the Ajax object sends a request to the Web server, it will wait for the completion of receiving the response data from the Web server before continuing to execute the subsequent code.

Because synchronous Ajax requests cause program blocking and adversely affect the user experience, synchronous requests are generally not recommended.

3.4 Processing information returned by the server

  • Get the current state of Ajax: readyState property

    • The readyState attribute is used to obtain the current state of Ajax. There are 5 forms of state values.

      status value illustrate explain
      0 Unsent The object has been created and the open() method has not been called yet
      1 Opened The open() method has been called. At this time, you can call the send() method to initiate a request.
      2 response header received The send() method has been called and the response header has been received
      3 Data receiving The response body is being received. responseText will have part of the response data during the loading process
      4 Finish Data reception completed. At this point you can get the complete response through responseText
    • In addition, the Ajax status can also be obtained through "XMLHttpRequest.Attribute name".

      XMLHttpRequest.UNSENT;		// 对应状态值0
      XMLHttpRequest.OPENED;		// 对应状态值1
      XMLHttpRequest.HEADERS_RECEIVED;	// 对应状态值2
      XMLHttpRequest.LOADING;		// 对应状态值3
      XMLHttpRequest.DONE;			// 对应状态值4
      
  • Perception of Ajax state changes: onreadystatechange event attribute

    • The onreadystatechange event attribute is used to sense changes in the status of the readyState attribute. This event will be called whenever the value of readyState changes.

      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
              
              
          console.log(xhr.readyState);
      };
      console.log(xhr.readyState);
      xhr.open('GET', 'test.php');
      xhr.send();
      
  • Returns the HTTP status code of the current request: status attribute

    • The status attribute is used to return the HTTP status code of the current request, and the value is a numeric type.
    • For example, when the request is successful, the status code is 200.
    • There is also a similar attribute statusText, whose value is character data and contains a description phrase, such as "200 OK".
  • Get response information: responseText attribute, responseXML attribute, etc.

    • When the request to the server is successful and data reception is completed, you can use the related properties provided by the Ajax object to obtain the server's response information.

      attribute name illustrate
      responseText Return response information as a string
      responseXML Format the response information into an XML Document object and return it (read-only)
    • The value of the responseXML attribute is null when the request fails or the corresponding content cannot be parsed.

    • It should be noted that the server should set the value of the response header Content-Type to text/xml or application/xml when returning XML, otherwise the parsing will fail.

    • How Ajax handles information returned by the server.

      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
              
              
          if (xhr.readyState === XMLHttpRequest.DONE) {
              
              
              if (xhr.status < 200 || xhr.status >= 300 && xhr.status !== 304) {
              
              
                  alert('服务器异常');
                  return;
              }
              console.log(xhr.responseText);
          }
      };
      xhr.open('GET', 'hello.php');
      xhr.send();
      

URL parameter encoding conversion

  • When passing data through URL parameters, problems may arise if the parameters contain special characters.

  • For example, "?", "=" and "&", these characters have been given specific meanings.

  • If you need to pass these special characters, you can use encodeURIComponent() for URL encoding.

    var str = encodeURIComponent('A&B C');
    var url = 'http://xxx/test?name=' + str;
    // 输出结果:http://xxx/test?name=A%26B%20C
    console.log(url);	
    
    • "&" is converted to "%26".

    • Spaces are converted to "%20".

    • When the server receives the encoded content, it decodes it to correctly recognize these special characters.

  • For already encoded strings, you can use decodeURIComponent() to decode them.

    var str = 'A%26B%20C';
    // 输出结果:A&B C
    console.log(decodeURIComponent(str));
    

4 Data exchange format

How to ensure that both front-end and back-end applications can recognize it when exchanging data?

Agree on a format to ensure that both communicating parties can correctly identify the information sent by the other party.

4.1 XML data format

XML: eXtensible Markup Language, extensible markup language.

Both HTML and XML are tag languages. XML is mainly used to describe and store data, and tags can be customized.

<!-- XML的声明 -->
<!-- version表示XML的版本,是声明中必不可少的属性,且必须放在第1位 -->
<!-- encoding用于指定编码 -->
<?xml version="1.0" encoding="utf-8" ?>
<!-- 开始标签 -->
<booklist>
    <book>
        <name>三国演义</name>
        <author>罗贯中</author>
    </book>
    <book>
        <name>水浒传</name>
        <author>施耐庵</author>
    </book>
<!-- 结束标签 -->
</booklist>

When the server returns data in XML format, the XML data can be processed using the responseXML attribute of the Ajax object.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    
    
    if (xhr.readyState === XMLHttpRequest.DONE) {
    
    
        var data = xhr.responseXML;
        var booklist = data.getElementsByTagName('booklist')[0];
        console.log(booklist.childNodes);
        var book = booklist.children[0];
        console.log(book.children[0].innerHTML);               // 方式1
        console.log(book.children[0].firstChild);              // 方式2(会加上引号)
        console.log(book.children[0].firstChild.wholeText);    // 方式3
    }
};
xhr.open('GET', 'xml.php');
xhr.send();

4.2 JSON data format

JSON: is a lightweight data exchange format.

Features: Using a completely language-independent text format, which makes JSON easier to parse and process by programs.

Compared with XML: It is more convenient to obtain data by using JSON objects to access attributes, and you can easily convert between JSON strings and objects in JavaScript.

Data interaction implementation in JSON format.

var obj = {
    
    name: 'Tom', age: 24};     // 准备要发送的数据
var json = JSON.stringify(obj);       // 将对象转换为JSON字符串
var xhr = new XMLHttpRequest();
xhr.open('POST', 'json.php');
xhr.onreadystatechange = function() {
    
    
    if (xhr.readyState === XMLHttpRequest.DONE) {
    
    
        var obj = JSON.parse(xhr.responseText);    // 将JSON字符串转换为对象
        console.log(obj);
        /*
        console.log(typeof xhr.responseText);     // 查看服务器返回数据的类型:string
        eval('var obj = ' + xhr.responseText);    // 用eval()函数将字符型转成对象
        console.log(obj.name);                    // 输出结果:Tom
        console.log(obj.age);                     // 输出结果:24
      */
    }
};
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('json=' + encodeURIComponent(json));

eval() function

The eval() function in JavaScript can execute the incoming string as JavaScript code.

console.log(typeof xhr.responseText); // 查看服务器返回数据的类型:string
eval('var obj = ' + xhr.responseText);  // 用eval()函数将字符型转成对象
console.log(obj.name);                         // 输出结果:Tom
console.log(obj.age);                    	   // 输出结果:24

When eval() sets parameters, if the incoming string is illegal, the subsequent code will not be executed, so it is generally not recommended to use it.

5 Cross-domain requests

5.1 Ajax cross-domain issues

  • Domain refers to an independently operating unit in the network.
  • From a network security perspective, domains are security boundaries. Each domain has its own security policy. Different domains are isolated and cannot access each other unless a trust relationship is established.
A网站 -> 利用Ajax读取用户在B网站中的余额 -> B网站
A网站 <- 通过Ajax向A网站发送修改密码的请求 <- B网站

Cross-domain requests cause the web page to lose security, so browsers block cross-domain requests.

How browsers solve the harm caused by cross-domain issues.

Follow the same-origin policy, which means that the protocol, domain name, and port in the requested URL address are the same.

Non-original URL address

question URL-1 URL-2
Domain names are different http://www.example.com/1.html http://api.example.com/1.html
Different protocols http://www.example.com/1.html https://www.example.com/1.html
Different ports http://www.example.com/1.html http://www.example.com:8080/1.html

Problems caused by browsers following the "same origin policy": It brings difficulties to the normal cross-domain requirements of the website.

One solution: To enable cross-domain access between trusted websites, HTML5 provides a new strategy, the Access-Control-Allow-Origin response header. The target server can specify to allow cross-domain requests from a specific URL through this response header, and its value can be set to any URL or a specific URL, etc.

header('Access-Control-Allow-Origin: http://localhost:8081');

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8082/8082');
xhr.send();

5.2 JSONP implements cross-domain requests

JSONP: A way to implement cross-domain requests based on the browser's same-origin policy.

Principle: It has nothing to do with XMLHttpRequest, but uses <script>the src attribute of the tag to implement cross-domain requests.

In the browser, which tags can load cross-origin resources? <script>、<img>、<iframe>、<link>Wait for labels.

  • The reason why JSONP uses <script>the tag is because the resources loaded by this tag can be directly executed as JavaScript code, and data can be transmitted as long as the server side cooperates.

  • JSONP cross-domain request.

JSONP essentially loads scripts from other websites, which poses security risks because other websites can use JavaScript to steal user information or change page content. Therefore, before loading the script, make sure that the other party is a trusted website.

Automatically generate JSONP callback function name

In actual development, using the above method to implement JSONP cross-domain requests still has the following two shortcomings.

  • The function name test() of the callback function will pollute the global scope.
  • When multiple JSONP requests need to be sent, each callback function cannot be distinguished.

In order to solve these two problems, we can write code to automatically generate a random callback function name, and pass the function name to the server when requesting, and the server calls the specified function in the return result.

function jsonp(url, callback) {
    
    
    var name = 'jsonp' + Math.random().toString().replace(/\D/g, '');
    window[name] = callback;
    var script = document.createElement('script');
    var attr = document.createAttribute('src');
    attr.value = url + '?callback=' + name;
    script.setAttributeNode(attr);
    document.body.appendChild(script);
};
jsonp('http://localhost:8082/test', function(data) {
    
    
    console.log(data);
});

6 Extension technologies

6.1 Cookie

Cookie: Also known as Cookies, it refers to the data stored on the client by some websites in order to identify users and track sessions.

Relevant response header: Set-Cookie field

Features: The next time you request the website, the browser will put the cookie data into the Cookie field in the request header. The server can identify the user status after receiving this data.

Cookies are stored based on domain name, path and other parameters. Cookies from different websites are isolated from each other to ensure data security.

6.2 FormData

How to collect data from a form when Ajax sends data to the server?

Previous method: Manually obtain the values ​​filled in by the user in the form through DOM manipulation.

Disadvantages: When there is a lot of data in the form, using this method will bring a lot of trouble to development and maintenance.

Methods provided by HTML5: FormData form data object.

Usage: Instantiate new FormData() and pass in <form>the form object.

After creating the FormData object, you can pass it in as a parameter when calling the send() method of the Ajax object to send the form data to the server.

<form id="form">
    姓名:<input type="text" name="name"><br>
    密码:<input type="password" name="password"><br>
    邮箱:<input type="text" name="email"><br>
    <input type="submit" value="提交">
</form>
<script>
    document.getElementById('form').onsubmit = function() {
      
      
        var fd = new FormData(this);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'test.php');
        xhr.send(fd);
        return false;  // 阻止表单默认的提交操作
    };
    /*
    var fd = new FormData();
    fd.append(name, value);
    */
</script>

6.3 Promise

Promise is a new object in ES6, used to deliver messages for asynchronous operations.

At the code level, Promise solves the "callback hell" problem of asynchronous operations.

"Callback hell" refers to the situation where callback functions are nested within callback functions when the next asynchronous operation is executed after an asynchronous operation is completed. If there are too many levels of nesting, the code will become less readable.

Setup.prototype.run = function() {
    
    
    this.step1(function() {
    
    
        this.step2(function() {
    
    
            this.step3(function() {
    
    
                // ……
            });
        });
    });
};
  • Ajax's onreadystatechange() is an asynchronous operation. If you need to issue another Ajax request after one Ajax request is completed, callback function nesting will occur.

  • Use the syntax provided by the Promise object to optimize Ajax operations.

    function xhr(options) {
          
          
        return new Promise(function(resolve, reject) {
          
          
            var xhr = new XMLHttpRequest();
            xhr.open(options.type || 'GET', options.url);
            xhr.onreadystatechange = function() {
          
          
                if (xhr.readyState === XMLHttpRequest.DONE) {
          
          
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
          
          
                        resolve(xhr.responseText);     // 成功时执行的函数
                    } else {
          
          
                        reject('服务器发生错误。');    // 失败时执行的函数
                    }
                }
            };
            xhr.send(options.data);
        });
    }
    
    var fd = new FormData();
    fd.append('num', 100);
    
    xhr({
          
          url: 'test.php', type: 'POST', data: fd})
        .then(function(data) {
          
          
        console.log('请求成功:' + data);
    }, function(err) {
          
          
        console.log('请求失败:' + err);
    });
    
    xhr({
          
          url: '1.txt', type: 'POST', data: fd})
        .then(function(data) {
          
          
        console.log('请求成功:' + data);
    })
        .catch(function(err) {
          
          
        console.log('发生异常:' + err);
    });
    
    xhr({
          
          url: 'test.php', type: 'POST', data: fd})
        .then(function(data) {
          
          
        console.log('第1次请求结果:' + data);
        return xhr({
          
          url: 'test.php', type: 'POST', data: fd});
    })
        .then(function(data) {
          
          
        console.log('第2次请求结果:' + data);
    })
        .catch(function(err) {
          
          
        console.log('发生异常:' + err);
    });
    

Fetch API

Reason proposed: The syntax of the XMLHttpRequest object is relatively complex.

Function: The new version of the browser proposes Fetch API, based on Promise syntax, to improve the readability of the code.

Tip: Since the Fetch API is currently an experimental feature and browser support is not comprehensive, it is not recommended to be used in online projects.

fetch('test.php', {
    
    
    method: 'POST', 
    headers: new Headers({
    
    
        'Content-Type': 'text/plain'
    })
}).then(function(response) {
    
    
    // 处理响应结果
}).catch(function(err) {
    
    
    // 处理错误
});

6.4 WebSocket

WebSocket: It is a new API for asynchronous communication between client and server in HTML5.

Function: Used to enable the browser to support the WebSocket network protocol.

Problem solved: HTTP polling.

HTTP polling: The client needs to continuously send HTTP requests to the server to ask the server if there are new messages. This method is called HTTP polling. The characteristic is that its communication efficiency is very low.

Solution: WebSocket implements full-duplex communication. After the connection is established, the server can actively push new messages to the client. This method is more real-time and more efficient.

// 创建WebSocket对象,连接服务器
var ws = new WebSocket('ws://127.0.0.1:2000'); 
// 当连接成功时执行的回调函数
ws.onopen = function() {
    
     
    console.log('连接成功');
    ws.send('Tom');
    console.log('向服务端发送一个字符串:Tom');
};
// 当收到服务器消息时执行的回调函数,event是事件对象
ws.onmessage = function(event) {
    
    
    console.log('收到服务器消息:' + event.data);
};

var ws = new WebSocket('ws://127.0.0.1:2000');
ws.onopen = function() {
    
    
    console.log('连接成功');
};
ws.onmessage = function(e) {
    
    
    console.log('收到服务器消息:' + e.data);
};

r) { // Handle errors });




### 6.4 WebSocket

WebSocket:是HTML5新增的一个客户端与服务器异步通信的API。

作用:用于使浏览器支持WebSocket网络协议。

解决的问题: HTTP轮询。

HTTP轮询:客户端需要不断向服务器发送HTTP请求,询问服务器是否有新的消息,这种方式称为HTTP轮询。特点是其通信效率非常低。

解决办法:WebSocket实现了全双工通信,在建立连接后,服务器可以将新消息主动推送给客户端,这种方式实时性更强,效率更高。

```js
// 创建WebSocket对象,连接服务器
var ws = new WebSocket('ws://127.0.0.1:2000'); 
// 当连接成功时执行的回调函数
ws.onopen = function() { 
    console.log('连接成功');
    ws.send('Tom');
    console.log('向服务端发送一个字符串:Tom');
};
// 当收到服务器消息时执行的回调函数,event是事件对象
ws.onmessage = function(event) {
    console.log('收到服务器消息:' + event.data);
};

var ws = new WebSocket('ws://127.0.0.1:2000');
ws.onopen = function() {
    console.log('连接成功');
};
ws.onmessage = function(e) {
    console.log('收到服务器消息:' + e.data);
};

Guess you like

Origin blog.csdn.net/zhangchen124/article/details/133375409