Tag Archives: JavaScript

Syntax error reported by JavaScript function: expected expression, got ‘;’

Story background: when writing a Java Web project and running under Firefox, firebug reports an error syntax error: expected expression, got ‘;’ Or syntaxerror: expected expression, got ‘if’, etc

Click the detailed code of error reporting on the firebug console and find that the code looks like this:

$(document).ready(function(){  
            var s = ;  
            if(s==null||s==""){  
                alert("Please Login");  
                location.href="/SSM0413/jsp/login.jsp";  
            }  
        });

But the code I wrote under eclipse is as follows:

    $(document).ready(function(){  
                var s = ${sessionScope.user.userName};  
                if(s==null||s==""){  
                    alert("Please Login");  
                    location.href="/SSM0413/jsp/login.jsp";  
                }  
            });

It is obvious that the variable assignment part ${sessionscope. User. Username} is gone. Can I use El expressions directly in JavaScript?The answer is: no

So how can we assign the value in the session to the variable in the JavaScript function?After searching the data, we get the following idea:

 

Write a span tag in the body and use the El expression in the span tag. However, in order not to create an additional span influence interface out of thin air, set the hidden attribute to hide it, such as:

    <span id="uu" hidden="hidden">${sessionScope.user.userName}</span>

Then use getelementbyid in JS to get the content in the span tag, and you can assign a value to the variable

    var s = document.getElementById("uu").innerHTML;

Summary: 1. El expressions cannot be used directly in JavaScript

2. In case of this problem, you can check the JS code first. In addition to the format problem, write more or less “;” Also, check whether some functions, libraries, or El expressions of the application can be used in JS code

3. Making good use of firebug can solve many problems

 

XHR request status is the solution to failed

After XHR request, the status is reported as failed, which is the request error
in this case, the first thing is to check whether the path of the request is correct, and the second is whether the parameters are correct
I check my specific request parameters, which should have related parameters, but the request is not displayed, I checked the code again

and found that my request failed due to the wrong address

Nuxt module build failed error report

Problem, in the process of nuxt development, run NPM run dev to report an error directly. The error information is as follows

 Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions.

Causes and Solutions

Reason: This exception indicates a version conflict in babel, a babel dependency package is not compatible, there is both babel version 7.0 and babel version 6.0 in the package.json dependency package.

The two versions are obviously incompatible, so we can upgrade all of them to babel 7.0.

Solution: Upgrade to babel 7.0 with npm install [email protected] and the version conflict will be solved.

Vue project webpack optimization compression webpack plugin open gzip

Abstract:

Starting gzip when packaging can greatly reduce the size of the package, which is very suitable for online deployment. Smaller size for user experience

It means faster loading speed and better user experience.

Vue-cli3.0 project

Installation dependency: compression webpack plugin

npm install compression-webpack-plugin –save-dev

vue.config.js Revision:

const CompressionPlugin = require('compression-webpack-plugin');

constproductionGzipExtensions=/.(js-124css-124json-124txt *)?$/i;

module.exports = {
    publicPath: './',
    productionSourceMap: false,
    configureWebpack: {...},
    chainWebpack: config =&> {
        config.resolve.alias.set('@', resolve('src'));
        if (process.env.NODE_ENV === 'production') {
            config.plugin('compressionPlugin')
            .use(new CompressionPlugin({
                filename: '[path].gz[query]',
                algorithm: 'gzip',
                test: productionGzipExtensions,
                threshold: 10240,
                minRatio: 0.8,
                deleteOriginalAssets: true
            }));
        }
    },
};

Parameter configuration of compression webpack plug in: View on the official website( https://www.webpackjs.com/plugins/compression-webpack-plugin/ )

Parameter configuration of compression webpack plug in: View on the official website(

Parameter configuration of compression webpack plug in: View on the official website(

gzip on;
gzip_static on;
gzip_min_length 1k;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
gzip_disable "MSIE [1-6].";

Gzip use environment: http, server, location, if (x), generally defined in nginx.conf Http { Between

  gzip on

on is enabled and off is off

gzip_ min_ length 1k

Set the minimum number of bytes of the page that can be compressed. The number of bytes of the page is obtained from the content length in the header. The default value is 0, no matter how many pages are compressed. It is recommended to set the number of bytes larger than 1K. If the number of bytes is less than 1K, it may increase.

gzip_ buffers 4 16k

How much memory is used to cache compression results?”4 16K” means to get the compression results in 16K * 4

  gzip_ comp_ level 5

Gzip compression ratio (1 ~ 9), the smaller the compression effect is, the worse the compression effect is, but the larger the processing speed is, the slower the processing speed is, so the intermediate value is generally taken

  gzip_ types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php

Takes effect for specific MIME types, where ‘text/HTML’ is forced to be enabled by the system

  gzip_ http_ version 1.1

Identify the version of HTTP protocol. Early browsers may not support gzip self decompression, and users will see garbled code

  gzip_ vary on

Enable reply header “vary: accept encoding”

  gzip_ proxied off

When nginx is used as a reverse proxy, it is enabled, off (compression of all proxy result data is turned off), expired (compression is enabled, if the header contains “expires” header information), and no cache (compression is enabled, if the header contains “cache” header information)- Control:no-cache “), no store (compression enabled, header header contains” cache “- Control:no-store “), private (compression enabled, The header contains “cache”- Control:private “),no_ last_ Modefied (compression enabled, header header does not contain “last modified”), no_ Etag (enable compression, if header does not contain “Etag” header information), auth (enable compression, if header contains “authorization” header information)

  gzip_ disable msie6

Ie5.5 and IE6 SP1 use the msie6 parameter to disable gzip compression) to specify which browsers (which will match with user agents) do not need gzip compression, depending on the PCRE library

Server configuration from juan26 = &> https://segmentfault.com/a/1190000012571492?utm_ source=tag-newest

Note: (gzip)_ Static on) the dynamic compression of nginx is to compress each request first and then output it, which causes the virtual machine to waste a lot of CPU. To solve this problem, we can use the nginx module gzip Precompression, this module is used to directly read the compressed file (file name is plus. GZ) for the file that needs to be compressed, instead of dynamic compression. For the request that does not support gzip, read the original file.

1. Files can be compressed using gzip or any other compatible command.

2.gzip_ Static configuration takes precedence over gzip.

3. Open nginx_ After static, we will first find out whether there is a corresponding GZ file for any file.

4.gzip_ Types setting to gzip_ Static is invalid.

5. Gzip static is applicable to HTTP 1.1 by default.

view the size comparison before and after compression:

Unpack



EnPack


Using CEF as user interface

Learn this, you can use local files to achieve a pure HTML, JavaScript and CSS (bootstrap) based user interface, and use it to operate the system

1、 Create a new folder in the project: HTML resources. Then copy the bootstrap file directory structure and content into it. And set the copy to output directory value of these files to copy always

2、 To display and manipulate index.html In the interface. Add button button to execute with JavaScript. (cefcustomobject is an instance of the operation class later)

<button class="btn btn-info" onclick="cefCustomObject.showDevTools();"&>Open Chrome Dev Tools</button&>
  <button class="btn btn-primary" onclick="cefCustomObject.opencmd();"&>Open cmd.exe</button&>

3. Create a new operation class (user target class) (click the button to perform the operation.) For example, opencmd method: open the CMD process

4、 In the constructor (1 — 4 is the same as using CEF as the browser)::

1. Cefsetting instantiation settings

2. Use CEF to initialize settings

3. Instantiate the chromiumwebbrower object (locally located) index.html (file)

4. Load this object into the control and set it to fill

5. The browser builds objects to register JS events. Binding instantiates the operation class.

6. Some browser properties are set by browersettings. Assigned to the browser.

Git source code address:

https://gitee.com/HuLuMiaoMiao/SecondCefSharp

Reference (some changes are easy to understand and some mistakes are made)

https://ourcodeworld.com/articles/read/173/how-to-use-cefsharp-chromium-embedded-framework-csharp-in-a-winforms-application

The difference between Top.location and window.location.href

top.location.href= ”URL “open URL on top page (jump out of frame)

self.location.href = “URL” only open the URL address on this page

parent.location.href= ”URL opens the URL address in the parent window

this.location.href= ”The usage of “URL” is consistent with that of self

if ( top.location == self.location )Judge whether the current location is the top level to prohibit frame reference. If there is a custom frame in the page, you can also change the parent self top to the name of the custom frame. The effect is to open the URL in the custom frame window.

In practice, it may be used as follows:

1 if(top !== self){            
2 
3    top.location.href = location.href;
4 
5 }   //Disable frame references

The following is an example found on the Internet, which is not very intuitive. I added the three lines of code above, which can be removed first and then added. If you look at the effect, it will be very clear.

top.htm Code:

 1 <script language=javascript>
 2 
 3    function rs(){
 4 
 5     if(top !== self){
 6 
 7       top.location.href = location.href;
 8 
 9       }
10 
11       parent.left.location.href="top.htm" ;
12 
13     parent.bot.location.href="top.htm";
14 
15       }
16 
17 < /script>
18 
19 < input type=button name=name value="ksdj" onclick=rs();>

Here is an HTM file with a random file name:

 1 <FRAMESET COLS="150,*">
 2 
 3     < FRAME SRC="left.htm" name=left>
 4 
 5     < FRAMESET ROWS="150,*">
 6 
 7          < FRAME SRC="top.htm" name=top>
 8 
 9          < FRAME SRC="bot.htm" name=bot>
10 
11     < /FRAMESET>
12 
13     < /FRAMESET>  

Try, it may be this effect

Top represents the main window and location represents the current window. If your file has only one frame and no iframe or frmaeset, it is completely consistent and no difference.

top.location Is to open a new page in the top-level frame window.location Is to open a new page in the current frame

parent.location Open URL address in parent window of current window

Windows 95 written in JavaScript can run on multiple platforms

Windows 95 written in JavaScript can run on multiple platforms

According to cnBeta, slack developer Felix rieseberg released Windows 95 as an electron application two years ago, which is written entirely in JavaScript. In the subsequent continuous update, it can run classic games such as “destroyer”. Now he’s rolling out a new version of Windows 95 electron that will run on windows, Mac OS and Linux.

Hard core Lao Wang comments: the omnipotent JavaScript actually reproduced the classic operating system of that year.

libresl is difficult to replace OpenSSL

According to solidot, the industry has been shaken by flaws in SSL infrastructure software. This led the CII and Linux foundation to fund the development of key components. The OpenBSD project created libresl, the branch of OpenSSL. This branch has been used and actively developed by OpenBSD distribution since then. However, the Linux world doesn’t buy it. OpenSSL is supported to a greater extent, which makes the OpenSSL project solve many of its long-term problems and make it more secure and stable.

As a result, very few Linux distributions migrate to libresl. Alpine and Gentoo distributions are trying to provide libresl, and alpine will soon return to OpenSSL; Gentoo’s support for libresl will end in February this year. Gentoo developers point out that libresl does not offer much benefit compared with OpenSSL, but increases the cost.

Hard core Lao Wang commented: this result is staggering. The incomplete and old software can actually be reborn, surpassing the new successors. It can be seen how much software inertia is.

US regulators consider allowing federal chartered banks to issue and promote stable currency

According to cnBeta, the office of the Comptroller of currency said in an explanatory letter that federal chartered banks and savings associations could consider using public blockchain and stable currency to carry out settlement business. This means that as long as existing laws are followed, banks can choose to use the public blockchain for verification, storage, recording and settlement. Or run your own encryption node and use the associated stable currency for licensed payment activities.

Hard core Lao Wang comments: it seems that the U.S. banking industry can not sit still.

XMLHttpRequest status=0 (All You Should Know)

error:function(XHR,textStatus,errorThrown){
            
            if (XHR.status == 403){
                var errMsg = XHR.responseText.replace(/\"/g,"");
                swal({
                     title:errMsg,
                     text:'3 s later will closed',
                     timer:3000,
                     type:'error'
                 });
            } else {
                swal({
                    title:'Internal server error,sorry!',
                    text:'3 s later will closed',
                    timer:3000,
                    type:'error'
                });
            }

original content

In fact, this article is not only about the problem of XMLHttpRequest status = 0, but also about some problems encountered by Ajax and my reflection.

Let’s look at the whole example


<html>  
<head>  
<script type="text/javascript">  
    var xmlhttp;  
    function loadXMLDoc(url) {  
        xmlhttp = null;  
        if (window.XMLHttpRequest) {// code for all new browsers  
            xmlhttp = new XMLHttpRequest();  
        } else if (window.ActiveXObject) {// code for IE5 and IE6  
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  
        }  
  
        if (xmlhttp != null) {  
            xmlhttp.onreadystatechange = state_Change;  
            xmlhttp.open("GET", url, true);  
            xmlhttp.send(null);  
        }  
    }  
  
    function state_Change() {  
        if (xmlhttp.readyState == 4) {  
            alert(xmlhttp.status);  
            alert(xmlhttp.responseText);  
            if (xmlhttp.status == 200) {  
                alert("200");  
            } else {  
                alert(xmlhttp.status);  
                alert("Problem retrieving XML data");  
            }  
        }  
    }  
</script>  
<title>Document</title>  
<button onclick="loadXMLDoc('file:///E:/test2.html')">click</button>  
</head>  
<body>  
</body>  
</html>  


1. Why xmlhttp.onreadystatechange = state_ Change instead of xmlhttp.onreadystatechange = state_ Change();

Isn’t it written in () to call a function?Does it look for a function based on its name?After asking a few front-end teachers, they felt that they were all vague and didn’t understand the real reason. Finally, they went to consult another elder martial brother.

The purpose is to give the entire function to onreadystatechange instead of returning the last processed value of the function to onreadystatechange.

Again, I saw the XMLHttpRequest object when I reread the XML tutorial recently, and immediately linked it with Ajax.

W3C, which is used to exchange data with the server in the background, is the developer’s dream .

Today’s browsers can get objects directly through new, but ie can’t, xmlhttp = new activexobject(“ Microsoft.XMLHTTP “);

At the same time, when IE6 is running, the browser will prompt you to set ActiveX.

Onreadystatechange is an event handle. It also has onclick functions. When there is a click event, it will be processed specifically. It depends on how your function is written. Onreadystatechange is triggered by readyState, which stores the state of XMLHttpRequest

0: request not initialized
1: server connection established
2: request received
3: request processing
4: request completed and response ready

When readyState is changed, call the onreadystatechange function. Note that this function is used. Do we want to assign a function to it instead of simply returning a value.

So the problem is solved.

At the same time, it is different from:

<button onclick="dodo()">click</button>  

This is in HTML. Although it is also an event handle, its format is different. The one above is in JS code.

2. XMLHttpRequest status = 0 problem.

xmlhttp.readyState =4, all the time xmlhttp.status ! = 200。 It’s easy to output and find out xmlhttp.status=0 There is no such status code in the HTTP protocol. Finally, we find a description of XMLHttpRequest http://www.w3.org/TR/XMLHttpRequest/ .

The status attribute must return the result of running these steps:

The status value must return the result of running these steps.

1. If the state is unsent or open, return 0.
2. If the error flag is set, return 0.
3. Return the HTTP status code

If the above two situations appear before HTTP returns, 0 will appear.

Let’s talk about two buttons, one is the URL: File:///E/test2.html, the other is: http://www.baidu.com .

The first button’s URL access is only opened locally, but not through the server. You can use Wireshark to catch packets (thank you for your advice).

There is also a problem, that is xmlhttp.readyState It always changes

1: Server connection established

2: Request received

3: Request processing

4: The request has completed and the response is ready.

In this case, xmlhttp should be simulating itself, because it didn’t pass the server at all. It’s just local. Open, so the status is 0.

Although the URL access of the second button is other domain names, packet capture is available, but it is cross domain access

If the cross-origin request status is network error

This is a network error.

Although I visited it, it should be because the browser’s cross domain return header is not allowed, so the browser blocks the access control allow origin attribute.

The real way is to visit the URL in your domain name on your own server.

Run on Tomcat:

<button onclick="loadXMLDoc('http://localhost:8080/TestServlet/MyServlet')">click</button>  

Finally, I’m reflecting. I’ve been looking for the answer to the question, but when I asked some of them, I just gave them the answers that came with Baidu. Some people even ignored this question after I said that there was a mistake after adding brackets, and they could use it. But I asked a senior brother not only this answer, because this senior brother is very good at the front end, and the most important thing is that he is a technology enthusiast. He gave me the analysis of the first question, and then he went to Google to go deeper.

The gap in technology is about this. It may not be big now, but in a few years, it is estimated that it will not be a level.

The difference between people is just the same.

Finally, I would like to thank another person, who let me see the experience of a full stack engineer. The front end and the back end are connected and killed, so are the bottom layer and the business logic. A few words can connect the things I checked in the afternoon, so does the so-called real programmer. I was very excited and admired to have a talk with him. People who love technology have nothing to do with it.