Category Archives: Javasript

[Solved] JS Ajax uploads an error “uncaught type error: illegal invocation”

When using jQuery Ajax to submit files asynchronously, an uncaught type error: illegal invocation error is reported. The error information is shown in the figure below:

error reason:

When using Ajax to send data to the background, the parameter type of the image data is file, which belongs to the object, not a string value. Causes the error to appear

var formData = new FormData();

formData.append(“src”, 2);

formData.append(“file”,imgFile);

First of all, we will see if the above problems are caused by the wrong writing of parameters. If it is written as an object by mistake, please modify the corresponding parameter type. If you are sure that one of the data to be uploaded is object type, please add it in the Ajax parameter

processData: false

contentType : false

      $.ajax({
              url: 'Transmission address',
              type: 'POST',
              cache: false,    //Uploading files without caching
              data: formData,
              processData: false, // Tells jQuery not to process the data sent
              contentType: false, // tells jQuery not to set the Content-Type request header
              success: function (res) {
                    console.log(res)
                    if(res.ret == 0){
                        console.log(Upload successful)
                    }
                },
                error: function (err) {
                    console.log(err)
                }
            })

>>

npm WARN saveError ENOENT: no such file or directory [How to Solve]

After node.js is installed, use NPM to install Vue. The error is as follows:

C:\Users\lxz> npm uninstall vueWcsp
npm WARN saveError ENOENT: no such file or directory, open ‘C:\Users\lxz\package.json’
npm WARN enoent ENOENT: no such file or directory, open ‘C:\Users\lxz\package.json’
npm WARN lxz No description
npm WARN lxz No repository field.
npm WARN lxz No README data
npm WARN lxz No license field.

Up to date in 0.765s
according to the error prompt, the system does not have the file package. JSON. This file is used to manage NPM packages installed locally. A package.json file can do the following:

The NPM package that the display project depends on
allows you to specify the version [scope] of a package
so that you can establish stability, which means that you can better share with other developers

Now we need to execute the order:

npm init

And then all the way back to OK, this file can be changed later

Create the package.json file, and the system will prompt for relevant configuration. You can also use the following command:

npm init -y

Create the package.json file directly. The advantage of creating this file is that the required items have been filled in for you. After executing the command, you can see that there is an additional package.json file in the user path

 

 

Resource interpreted as Stylesheet but transferred with MIME type text/html: css not work

Exception information:

Resource interpreted as Stylesheet but transferred with MIME type text/html:

Possible causes

The filter or some place turns all resource requests to text/HTML

Inspection method

Using browser to view request header and response header

Mainly check the content type of request header and response header

The style sheet should be text/CSS, and the request sent to the server and the server’s response to the client should be text/CSS

The problem I personally encountered in the project is that when using the filter to code all requests, the CSS file is also processed

The filter code before modification is

      System.out.println("**********AllFilter start work*********");
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)res;
       response.setCharacterEncoding("text/html; charset=UTF-8");

Treatment method

The request should be classified. When it is a kind of file such as CSS, it is requested in the original way and not processed. Other requests are processed again. The modified code is as follows:

System.out.println("**********AllFilter start work*********");
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)res;

        String url=request.getRequestURI();
        System.out.println("url:" +url);
        if(url.indexOf(".css")>0||url.indexOf(".js")>0||url.indexOf(".png")>0) {
            chain.doFilter(request, response);
            return;
        }
        response.setContentType("text/html;text/html; charset=UTF-8");
        
        

Solutions to nuxt error reporting require self closing on HTML elements (< div >) Vue / HTML self closing

First find the .eslintrc.js file

Then add the following configuration in the rules

" vue/html-self-closing " : [ " error " ,{
       " html " : {
         " void " : " never " ,
         " normal " : " any " ,
         " component " : " any "
      },
      " svg " : " always " ,
       " math " : " always " 
    }]

 

ok, solve the problem perfectly

The complete configuration is as follows

  rules: {
     ' no-console ' : process.env.NODE_ENV === ' production ' ? ' error ' : ' off ' ,
     ' no-debugger ' : process.env.NODE_ENV === ' production ' ? ' error ' : ' off ' ,
     ' generator-star-spacing ' : ' off ' ,
     " vue/html-self-closing " :[ " error ",{
       " html " : {
         " void " : " never " ,
         " normal " : " any " ,
         " component " : " any "
      },
      " svg " : " always " ,
       " math " : " always "
    }]
  }

 

Js Error: SyntaxError: identifier starts immediately after numeric literal

SyntaxError: identifier starts immediately after numeric literal

Today I wrote a onclick() method, there is such a variable 4028b88161c881ff0161c88b80dc0002

I need to pass the value of this variable into the method, but it never works:

I found that directly var aa =4028b88161c881ff0161c88b80dc0002 ;js is holding the error

The solution is as follows:

 

$(function(){
var str = “509edbe9-2914-431f-9128-97d368b7da0b”;

//The wrong way to write it
var html = ‘<button class=”button” id=”ensure” onclick=”test(str)”>OK</button>’;// Passing a string as an argument to a function reports an error directly

//The correct way to write it

var html = ‘<button class=”button” id=”ensure” onclick=”test(\”+str+’\’)”>OK</button>’;//execute correctly, note that the first \ is followed by two single quotes

$(“#dd”).append(html);

});
function test(id){
console.log(id);
}
<div id=”dd”></div>

VUE Run Error: This relative module was not found:

This error is reported when running the vue project.

This relative module was not found:



* ../../assets/img/spot.png in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/online

Maybe there is a problem with the introduction of spot.png into online.vue, the path is wrong or the file does not exist, and the same is true for similar problems

Bootstrap switch Uncaught TypeError: Cannot read property ‘apply’ of undefined

<input type=”checkbox” name=”my-switch” checked>

js write the following code, otherwise the switch control will not come out

$(“[name=’my-switch’]”).bootstrapSwitch();

$(‘[name=”my-switch”]’).bootstrapSwitch({

onText:”run”,

offText:”stop”,

onColor:”success”,

offColor:”info”,

size:”small”,

onSwitchChange:function(event,state){

if(state==true){

$(this).val(“1”);

}else{

$(this).val(“2”);

}

}

})

 

<div class="make-switch" data-on-label="开" data-off-label="关" id="toggle-state-switch" data-on="success" data-off="warning">
    <input id ="toggle" type="checkbox"  checked="checked" class="toggle"  />
</div>

function changeState(stateValue){
        if(stateValue==1){
            $('#toggle-state-switch').bootstrapSwitch('setState', true);
        }else{
            $('#toggle-state-switch').bootstrapSwitch('setState', false);
        }
}

Use the above method

$(‘#toggle-state-switch’).bootstrapSwitch(‘setState’, false); There is a problem

It should be used

$(‘#toggle-state-switch’).bootstrapSwitch(‘state’, true/false);

Another pit is to use the ID of the external div to set the state of the bootstrap switch, and there will be more nodes, as follows:

This is not the result we want, so it is wrong to set the value of external Div. The ID of the check box should be set as follows:

$(‘#toggle’).bootstrapSwitch(‘state’, false);

When assigning a value to the bootstrap switch, an error
uncaught type error: cannot read property 'apply' of undefined is prompted


        if (isUp==undefined || isUp == ''){
            $('#isUp').bootstrapSwitch('setState',true);
        } else{
            $('#isUp').bootstrapSwitch('setState',isUp);
        }

The detailed error information is shown in the following figure:

I refer to this setting and use jQuery to get the value of bootstrap switch
it seems that there is a problem, so I check the source code. There is no setstate method at all. I should use the following method:

if(stateValue==0){
            $('#toggle').bootstrapSwitch('state', true);
            console.log("Status enabled or not 1:",stateValue);
        }else{
            console.log("Status enabled or not 2:",stateValue);
            $('#toggle').bootstrapSwitch('state', false);
        }

JS Unexpected syntax error: unexpected string

JS error, finally found that the $(function () {}) part () is incomplete

$(function({
        $("#directionSelect").change(function(){
         
            $.ajax({
                url:"",
                success:function(data){
                    if(data.state=="fail"){
                        alert("The system is busy, please try again later!");
                    }else{
                     
                    }
                }
            });
        });
    });

After summarizing the previous errors, it is found that most of the errors are incomplete symbols, such as missing a bracket or a quotation mark

Json Uncaught SyntaxError: Unexpected token ‘ Uncaught SyntaxError: Unexpected number

The unexpected number (index) error uses the JSON string, such as

var jsonStr = "{1:'Beijing note docket information',2:'Shanghai note docket information',3:'Guangdong note docket information',4:'Shenzhen note docket information 4',5:'Tianjin note docket information 5',6:'Hubei note docket information 6',7:'Chongqing note docket information 7',8:'EU note docket information 8',9:' California note docket information 8',10:'Canada Quebec note information',11:'Northeastern United States RGGI Association Organization',12:'Australia note information',13:'New Zealand note information',14:'Tokyo note information 11111',15:'Korea Seoul information',16:'Switzerland information note'}";

This string can be parsed normally with open source China and other json formatting, but jquery parsing errors do not recognize your set, so I had to look for errors.

Uncaught syntax error: unexpected token ‘error string, such as:

var jsonStr = "{'Beijing':1,'Shanghai':2,'Guangdong':3,'Shenzhen':4,'Tianjin':5,'Hubei':6,'Chongqing':7,'EU':8,'California':9,'Quebec, Canada':10,'RGGI, USA':11,'Australia':12,'New Zealand':13,'Tokyo':14,'Korea':15,'Switzerland':16}"

Using json formatting tool is also error-free, had to find jquery documentation to see jquery.parseJSON() usage . The example given is as follows.

Parsing a JSON string

jQuery Code:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" ); I think it is the problem of single quotes and double quotes in it, now there is no other solution, so I have to change it by example, and the result is really successful. I think the jquery source code did not do the processing of the symbols inside the string to determine what kind of single quotes it contains.

If you find a solution to the problem, it’s easy to start

The JSON string is pieced together from the background, because the areaid is regarded as the key part, and the result is directly jsonstr. Append (‘”‘ + etsmapinfo. Getaeid() + ‘”); It turns 1 to 69. I don’t understand. But I next ruthless move just, outside first to turn into the string. Alas

I feel that solving problems first is the priority

The code in the string has a newline, and jQuery parsing will report an error just like what. You need to replace the newline symbol with a replacement function. As follows:

  var jsonStrRep = '${jsonStr}'.replace(/\r\n/g,"");
    jsonStrRep = jsonStrRep.replace(/\n/g,"");

Uncaught Error: Bootstrap’s JavaScript requires jQuery at bootstrap.min.js:6

The order of bootstrap is introduced to modify

<%
        //Get the part that starts with / and does not end with /
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <script src="${APP_PATH}/static/js/jquery-1.12.4.min.js"></script>

    <!-- The latest Bootstrap core JavaScript files -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    <!-- The latest version of Bootstrap's core CSS files -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

You need to introduce JavaScript first, then CSS