Analysis of the front-end docking problem

Analysis of the front-end docking problem

One, JSON

Concept:
JavaScript Object Notation JavaScript object notation (early period: in JavaScript, json was used to represent objects)

Example: var p = {"name":"Zhang San", "age": "23", "gender": "男"};

JSON is usually used to exchange data with the server. When receiving server data, it is usually a string. We can use the JSON.parse() method to convert the data into JavaScript objects.
Syntax: The
data is in a name/value pair: json data is a key composed of key-value pairs, enclosed in quotation marks (single and double), or without quotation marks.
The value type of the value :

  1. Number (integer or floating point)
  2. String (in double quotes)
  3. Logical value (true or false)
  4. Array (in square brackets) {"persons":[{},{}]} (can contain multiple persons)
  5. Object (in curly brackets) {"address":{"province":"Shaanxi"...}}
  6. null

note:

Data is separated by commas: multiple key-value pairs are separated by commas.
Curly brackets save the object: use {} to define the json format.
Square brackets save the array: []

Original link: https://blog.csdn.net/weixin_46008168/article/details/106314239

二 、 AJAX

AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).

Concept : Ajax makes the web page refresh asynchronously, refreshing part of the web page without reloading the entire page.

Ajax attributes : cache, processData, contentType
cache:
After a request is initiated, the cache will store the results obtained in the form of a cache. When the request is initiated again, if the value of the cache is true, it will be directly read from the cache , Instead of making a request again.
It can be concluded from the working principle of cache that the function of cache is generally only used in get requests.

processData: Process data
By default, the value of processData is true, which means that all the data uploaded in the form of objects will be converted into strings and uploaded. When uploading a file, you don't need to convert it to a string, so change it to false.

contentType: The format of the sent data
and the contentType have a similar attribute is dataType, which represents the format of the data expected to be received from the backend. Generally, there will be json, text... etc., and the contentType corresponds to the dataType. It represents the format of the data sent by the front end

Default value: application/x-www-form-urlencoded
represents ajax data. It is in the form of a string such as id=2019&password=123456.
Using this data format, it is impossible to transmit complex data, such as multi-dimensional arrays, files, etc.

Sometimes you need to pay attention to whether the data format you are transmitting is consistent with the contentType format of ajax. If it is inconsistent, you must find a way to convert the data. Changing the contentType to false will change the previous default data format. No error will be reported.

Original link: https://blog.csdn.net/qq_41564928/article/details/90580375

Parameter introduction:

$.ajax( [settings] ); //The parameter settings is the parameter list of the $.ajax () method, which is used to configure the key-value pair collection of the Ajax request;
Insert picture description here
Insert picture description here

Ajax package based on jQuery

$.ajax({
    
    
    type:'GET',	//请求的类型,GET、POST等	
    url:'www.baidu.com',	//向服务器请求的地址。
    contentType:'application/json',	//向服务器发送内容的类型,默认值是:application/x-www-form-urlencoded
    dataType:'JSON',	//预期服务器响应类型
    async:true,	//默认值是true,表示请求是异步的,false是同步请求,同步请求会阻碍浏览器的其他操作(不建议使用)
    timeout:'5000',	//设置本地的请求超时时间(单位是毫秒)
    cache:true,	//设置浏览器是否缓存请求的页面
    success:function(result,status,XMLHttpRequest){
    
    		//请求成功是执行的函数,result:服务器返回的数据,    status:服务器返回的状态,
              },
    error:function(xhr,status,error){
    
    	//请求失败是执行的函数
              },
    complete:function(xhr,status){
    
         //不管请求失败还是请求成功,都执行的函数
              }
            })

The parameter description in the code can also be seen in the link below:

Original link: https://blog.csdn.net/qq_32325367/article/details/52291889

Application example:

Note: The parameter syntax of the $.ajax() method is special. The parameter list needs to be contained between a pair of curly braces "{ }", and each parameter is written in the form of "parameter name": "parameter value"; if there are multiple parameters, separate them with a comma ",";

function addmovie(){
    
    
  var inputvalue = document.getElementById("inputmovie").value;//获取input框的内容
  console.log(inputvalue);//打印查看
  $.ajax({
    
    
    method: 'POST',//请求方式
    processData: false,
    url: '/api/movie/add',// 请求路径
    contentType: "application/json;charset=UTF-8",
    dataType:"json",//设置接受到的响应数据的格式
    data:JSON.stringify({
    
     //请求参数
      name:inputvalue,
    }),
    success(res) {
    
    
      try {
    
    
        if(res.code==200)
        {
    
    
          movielist();
        }
      }catch(e) {
    
    
        console.log(e)
      }
    },//响应成功后的回调函数
    error(e) {
    
    
      console.log('xhr error code is ' + e)
    }//表示如果请求响应出现错误,会执行的回调函数
  })
}

Analysis: The above code is much more concise and clearer than the native JavaScript implementation of Ajax. It only needs to set a few parameters. Among them, the success function is used to deal with the response, which is equivalent to the branch that should be successful in the callback number when the native JavaScript implements Ajax; the error function is equivalent to the error branch, in which the operation after the program error is performed, such as giving a message Wait. In addition, it should be noted that the parameters that do not need to be specially set can be omitted;

Three, MD5

MD5 (one-way hash algorithm) stands for Message-Digest Algorithm 5 (message-digest algorithm), developed from MD2, MD3 and MD4.

Application Environment:

When transmitting sensitive and private information such as card numbers and passwords, it is easy to use the get method to expose the password and user name in the rl, and the post method to easily find the data information on the console, so the MD5 method is used to encrypt the password.

Function:
input information of any length, after processing, the output is 128-bit information (digital fingerprint);
different results obtained by different inputs (uniqueness);
it is impossible to infer the input information based on the 128-bit output result (irreversible) );

Introduce js:

<script src="js/md5.js" type="text/javascript"></script>

Commonly used functions:

hex_md5(value)

b64_md5(value)

str_md5(value)

hex_hmac_md5(key, data)

b64_hmac_md5(key, data)

str_hmac_md5(key, data)

Example:

var password="hello"; 

var md5password = hex_md5(password);  

Four, cookie

The browser temporarily stores some data, stored on your computer (last access time, when you log in, you need to save the user name, and then display "Welcome, user name!" and other data on the home page after login)

Introduce js:

<script src="cookie.js"></script>

Example of use:

Cookies.set("username",username);//设置cookie
Cookies.remove("username");//删除cookie
Cookies.get('name');//获取cookie

Five, JQuery package

Concept:
jQuery = javaScript + Query to quickly query page elements through js code

The JavaScript function code is encapsulated inside it to optimize HTML document processing, event processing and AjAX interaction.

note:

jquery itself is a JavaScript function library, so you can write jquery code directly in the js file. The use of jquery needs to refer to the official jquery.js file. (The independent js file does not need to refer to any jquery.js file, only the jquery.js and .js files need to be quoted in the corresponding html web page. The jquery file reference must be before the .js file .)

Introduce js:

<script src="./js/lib/jquery-3.4.1.js"></script>

The related grammar can be found in the following link:

Original link: https://blog.csdn.net/qq_34477549/article/details/52821889

Six, the form of front-end request parameters

GETAnd POSTtwo ways
GET to obtain data from the specified server, POST to submit the data to the specified server for processing

In the GET method, the parameters in the data are spliced ​​into the url, in the POST method, the data is converted into json and sent.

Seven, on the resolution of cross-domain issues

What is a cross-domain issue?

The browser's same origin policy rejected our request. The so-called same origin means that the same domain name, protocol, and port are the same, and the script with the same origin will be executed when the browser executes a script. If it is not of the same origin, when requesting data, the browser will report the above exception in the console, prompting to deny access. This is to protect your website A login information from being used by website B to visit website A when you open multiple websites in the same browser. The same is true for website B login information.

For example: the address of the front-end project after running locally is http://localhost:8080/, at this time, if you want to access the back-end interface http://192.168.123.43:8000/api/xxx/xxx, you will encounter cross-domain problems Can not access.

Same Origin Policy: https://developer.mozilla.org/zh-CN/docs/Web/Security/Same-origin_policy

# 同源的例子
http://example.com/app1/index.html  # 只是路径不同
http://example.com/app2/index.html
 
http://Example.com:80  # 只是大小写差异
http://example.com
# 不同源的例子
http://example.com/app1   # 协议不同
https://example.com/app2
 
http://example.com        # host 不同
http://www.example.com
http://myapp.example.com
http://example.com        # 端口不同
http://example.com:8080
How to solve cross-domain problems?

Use nginx to solve

nginx

Reverse proxy: In fact, the client is unaware of the proxy, because the client can access without any configuration, we only need to send the request to the reverse proxy server, and the reverse proxy server selects the target server to obtain the data. When returning to the client, the reverse proxy server and the target server are external servers, exposing the proxy server address and hiding the real server IP address.

The difference between reverse proxy and forward proxy is: forward proxy proxy client, reverse proxy proxy server.

Original: https://www.cnblogs.com/ysocean/p/9392908.html#_label0

Nginx instructions:

start nginx #启动
nginx -s reload #重新加载Nginx配置文件,然后以优雅的方式重启Nginx
nginx -s stop #强制停止Nginx服务

8. How to fill our page with the json data returned by the backend

Method: Use a template engine

Template engine

The template engine is a third-party module.

Let developers splice strings in a more friendly way, making the project code clearer and easier to maintain .

art-template template engine

One, template syntax

Standard syntax: easy to read and write.

{
    
    {
    
    if user}}
<h2>{
    
    {
    
    user.name}}</h2>
{
    
    {
    
    /if}}

Original grammar: powerful logic processing capabilities.

<% if (user) {
    
     %>
<h2><%= user.name %></h2>
<% } %>

Two, installation

Use the npm install art-templaet command in the command line tool to download

3. How to use

1. Introduce a template engine

<script src="template-web.js"></script>

2. Create a template in html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="box">
        <!-- 创建script标签创建模板 -->
        <!-- 1. type="text/该斜杠后可以是 html,template... 不是script即可)" -->
        <!-- 2. 给 script 标签添加 id ,此 id 即为模板 id (也就是moviescript)-->
        <!-- 3. leval_1是对象,index-1是下标(也可用$value代替) -->
        <script id="moviescript" type="text/html">
            {
     
     {
     
     each shuffling leval_1 index_1}}
                <h1>{
     
     {
     
     leval_1.name}}</h1>
            {
     
     {
     
     /each}}
        </script>
    </div>
</body>
</html>
<!-- 引入模板引擎 -->
<!-- 注意:JS由于是解释型语言,是从上到下的顺序执行的,所以对于JS代码的引入一定要按照顺序,否则会报错
(后面的可能包含前面的,所以报错) -->
<script src="template-web.js"></script>
<script src="index.js"></script>

3. Create template() method

//数据内容
var mydata =[
    {
    
    
      name:'哈利波特',
    },
    {
    
    
      name:'匆匆那年',
    },
    {
    
    
      name:'哪吒',
    },
    {
    
    
      name:'漫威',
    },
  ]
  //获取html中需要被渲染的div盒子
  var movieget = document.querySelector('.box');
  //在控制台中打印相关信息
  console.log(movieget);
  // 基于模板名渲染模板,template(filename/id, data);
  //data即为后端传送过来的data主要渲染的信息,shuffling为index.html页面语法的变量名
  var moviexuanran = template('moviescript',{
    
    
    //第一种
    shuffling:mydata,
    //第二种:存放mydata.js里的json内容 
    shuffling:[{
    
    ……}],
  })
  //在定位的div盒子里innerHTML渲染的信息(写入)
  movieget.innerHTML = moviexuanran;

Four, grammar

The following uses standard grammar (support basic templates and basic js expressions) as examples

1. Output

{
    
    {
    
    value}}
{
    
    {
    
    data.key}}
{
    
    {
    
    data['key']}}
{
    
    {
    
    a ? b : c}}
{
    
    {
    
    a || b}}
{
    
    {
    
    a + b}}

2. Original output

{
    
    {
    
    @ value}}

3. Conditional output

<!--if 判断 -->
{
    
    {
    
    if value}} 
... 
{
    
    {
    
    /if}}

<!-- if ... else ... 判断 -->
{
    
    {
    
    if v1}} 
... 
{
    
    {
    
    else if v2}}
 ... 
{
    
    {
    
    /if}}

4. Traverse

{
    
    {
    
    each target}}
  {
    
    {
    
    $index}} {
    
    {
    
    $value}}
{
    
    {
    
    /each}}

Note: Ittarget is an array, eachused to traverse the array, $indexis the subscript $valueof the array , is the value of the array

5. Sub-template

Use sub-templates to extract the public sections (head, bottom) of the website into separate files.

{
   
   {include '模板'}}
{
   
   {include './header.art'}}
{
   
   {include './header.art' data}}

6. Template inheritance

Using template inheritance can extract the HTML skeleton of the website into a separate file, and other page templates can inherit the skeleton file.

{
   
   {extend './layout.html'}}
{
   
   {block 'head'}}
...
{
   
   {/block}}

Original: https://www.jianshu.com/p/d8d8e19157e0

Disclaimer: Part of the information comes from the Internet, if there is any infringement, please contact me to delete it!
If there are errors, confusions, etc. in the article, criticisms and corrections are welcome!

Guess you like

Origin blog.csdn.net/hxtxsdcxy/article/details/114989531