Category Archives: JavaScript

for..in loops iterate over the entire prototype chain, which is virtually never what you want.

for..in loops iterate over the entire prototype chain, which is virtually never what you want.

It means that using for..in will traverse the entire prototype chain, which is not a good way to implement it. Object.keys is recommended

formRules : {
  name : true,
  cardType: true,
  certificateNo: true
 },
 formData : {
  name :  '' ,
  certificateType:  '' ,
  certificateNo:  ''
 }

Original code

for ( const key in  this .formData) {
     if (! this .formData[key]) { this .formRules[key] = false ; valid = false }
     if ( this .formData[key]) this .formRules[key] = true
}

Modified code

Object.keys( this .formData).forEach(key => {
 if (! this .formData[key]) { this .formRules[key] = false ; valid = false }
 if ( this .formData[key]) this .formRules[key] = true
})

How to solve Uncaught (in promise) error in VUE?

When writing the vue project interface today, there was an Uncaught (in promise) error error.

 

 

 

I took a closer look, the interface is ok,

 

 

 

Me where the problem seems to have nothing, why the console which will be reported this wrong?

 

Later I found out that I did not write catch and he forcibly threw the error, so I changed the code to the following.

 

 

 

 

But after the change, it did not report the Uncaught (in promise) error error, and the other errors were reported, and a bunch of such errors were reported ↓

 

 

 

 

 

Reported so many mistakes, almost forced me. (But don’t panic, raise Erlang’s legs, drink a glass of water, and continue to look down)

 

 

      .catch(err=>{
this.$message.error(err.message);
console.log(err);
})

 

Just write message after err.

Special JSON array of special bracket

	@Test
	public void demo93() throws Exception {
		String str = "[\"a\", \"b\", \"c\"]";
		//Generate json arrays
		JSONArray createArray = new JSONArray();
		createArray.put("a");
		createArray.put("b");
		createArray.put("c");
		System.out.println("createJSONArray: " + createArray);
		//Parsing json arrays
		JSONArray parseArray = new JSONArray(str);
		System.out.println("parseJSONArray: " + parseArray);
		for(int i = 0; i < parseArray.length(); i++) {
			System.out.print(parseArray.get(i) + " ");
		}
	}

Output:

The solution of calling$. Ajax successfully but the success method does not respond

Today, when I was working, I encountered a problem. I used $. Ajax to transfer data to the background, which can operate correctly in the background, but success did not respond, and error responded. After checking the document, I realized that after jQuery version 1.4, all the returned JSON formats must meet the requirements json.org Success can only be called back correctly in the format of, otherwise jQuery will think that it returns an error Here is an example:

JSONObject j = new JSONObject();
j.put("msg","SUCCESS");
PrintWriter out = response.getWriter();
out.write(j.toString());

This is correct. JQuery calls back success

String j = "123";
PrintWriter out = response.getWriter();
out.write(j);

This is wrong, jQuery will think it is wrong

 

Method of adding operation button for each line of data in DataGrid of easyUI

When I was working on the project today, I wanted to add an operation button after each column of data in the DataGrid of easyUI. At the beginning, I wanted to splice strings in the background and return them with JSON. But after testing, I found that this method didn’t work. I searched the Internet and sorted them out as follows:

In fact, it’s very easy to add a row of custom columns. When JS declares DataGrid, add the following code

<span style="font-size:18px;">{field:'operate',title:'act',align:'center',width:$(this).width()*0.1,
	formatter:function(value, row, index){
		var str = '<a href="#" name="opera" class="easyui-linkbutton" ></a>';
		return str;
}}</span>

This line of code is defined under the columns property, and it must be added

<span style="font-size:18px;">onLoadSuccess:function(data){  
        $("a[name='opera']").linkbutton({text:'buy',plain:true,iconCls:'icon-add'});  
},</span>

If you don’t add this, there will be no button style in that operation column. It’s just a hyperlink. You can use LinkButton or other buttons according to your needs

 

 

Summary of jQuery autocomplete plug-in

Requirement: realize the prompt effect similar to Baidu search, that is, you can filter the options in the drop-down list through keywords

There are ready-made autocomplete plug-ins in layui and iView, but they need to integrate the dependencies related to layui and iView. I just want to realize this function in a simple business environment, and there is no integrated environment in the business framework of the system, so this method has low cost performance.

I found a case of using jQuery for integration on the Internet and studied it by myself. The notes in the original chestnut are not very clear, which is not easy for people like me who have not understood and studied the autocomplete component of jQuery before. Don’t talk too much nonsense. Paste the effect picture first

The above screenshot is an example, which I used for integration in my project. Ajax can achieve real-time access and fixed source array filter values. Next, I will post the codes of the two examples:

The first method is to use source array

    var countries = {
        "AD": "Andorra",
        "A2": "Andorra Test",
        "AE": "United Arab Emirates",
        "AF": "Afghanistan",
        "AG": "Antigua and Barbuda"
        }
    var countriesArray = $.map(countries, function (value, key) { return { value: value, data: key }; });
    $('#autocomplete-ajax').autocomplete({
        lookup: countriesArray,   // If this attribute is written, it means that a fixed array of data is used, even if the serviceUrl attribute is also available, it will not take effect
        lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
            var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
            return re.test(suggestion.value);
        },
        onSelect: function(suggestion) {
            $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
        },
        onHint: function (hint) {
            $('#autocomplete-ajax-x').val(hint);
        },
        onInvalidateSelection: function() {
            $('#selction-ajax').html('You selected: none');
        }
    });

The second way: Ajax real-time access

    var countriesArray = $.map(countries, function (value, key) { return { value: value, data: key }; });

    //jQuery ajax mock,Simulate background processing of incoming requests
    $.mockjax({
        url: '*',
        responseTime: 2000,
        response: function (settings) {
            var query = settings.data.query,
                queryLowerCase = query.toLowerCase(),
                re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi'),
                suggestions = $.grep(countriesArray, function (country) {
                     // return country.value.toLowerCase().indexOf(queryLowerCase) === 0;
                    return re.test(country.value);
                }),
                response = { // Note that the return format must be in this format
                    query: query,
                    suggestions: suggestions
                };

            this.responseText = JSON.stringify(response);
        }
    });
    // Initialize ajax autocomplete:
    $('#autocomplete-ajax').autocomplete({
        serviceUrl: '/autosuggest/service/url',
        // lookup: countriesArray, // This must be commented out, otherwise the countriesArray array in the property will be used instead of taking the ajax request in the serviceUrl
        lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
            var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
            return re.test(suggestion.value);
        },
        onSelect: function(suggestion) {
            $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
        },
        onHint: function (hint) {
            $('#autocomplete-ajax-x').val(hint);
        },
        onInvalidateSelection: function() {
            $('#selction-ajax').html('You selected: none');
        }
    });

In this way, we need to pay attention to the following points:

    1. when using serviceurl, the lookup attribute must be commented out; the serviceurl attribute is configured with the real request path of the background, and the above configuration is to simulate the background processing by using mockjax, and the corresponding mockjax code does not need to be reflected in the program; the format of the data returned by the background must be strictly in accordance with: {“query”: query, “suggestions”: suggestions}, Suggestions is the filtered data, and you can debug the specific format to understand it; </ OL>

The following is my own specific code:


$(function () {
    'use strict';

    // Initialize ajax autocomplete:
    $('#autocomplete-ajax').autocomplete({
        serviceUrl: 'http://127.0.0.1/test/autosuggest/userInfo/4028805e6d5e3155016d637627d80157',
        lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
            var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
            return re.test(suggestion.value);
        },
        onSelect: function(suggestion) {
            $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
        },
        onHint: function (hint) {
            $('#autocomplete-ajax-x').val(hint);
        },
        onInvalidateSelection: function() {
            $('#selction-ajax').html('You selected: none');
        }
    });
    
});

last:

You are welcome to exchange and study with me. Because this article was written after the event, I can’t remember which God’s code was written at that time. The source code has to be written down. The website is as follows: www.jq22.com , the specific use of the case has not been found, the following is the source code link I downloaded before, can be downloaded for free, if there is infringement, please contact to delete.

be careful:

1. When using Ajax dynamic request, the plug-in will pass a query parameter to the background: I use @ requestparam (name = query “, required = false) string query to accept it;

2. When using Ajax dynamic request, the return format is fixed, and the name of the return attribute should not be modified. The return format code is as follows

@Getter
@Setter
@ToString
public class Result1 implements Serializable {

	@ApiModelProperty("Query criteria")
	private String query;
	
	@ApiModelProperty("return output")
	private List<Result12> suggestions;
}

@Getter
@Setter
@ToString
public class Result12 implements Serializable {

	@ApiModelProperty("name")
	private String value;
	
	@ApiModelProperty("key")
	private String data;
}

The reason why jQuery files report errors is introduced

JS file import location is fastidious , Otherwise, an error will be reported

The above three arrows point to the JS is written by themselves, some may use the JQ framework, so if the JQ is placed below the three, the following three with JQ will report an error.
So pay attention when referencing to see if each JS referenced is independent or dependent on a JS, independent then the location will not have an impact, such as layui.js, but there are dependencies then the location will have an impact, such as the three JS arrows, you must refer to the JS he depends on before referencing in

[Solved] Vue cli installation Fastclick Error

When I installed the fastsclick package into the vue-cli dependency today, it reported an error saying

$ npm install fastclick –save
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! network request to https://registry.npm.taobao.org/fastclick failed, reason: getaddrinfo ENOTFOUND registry.npm.taobao.org
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network ‘proxy’ config is set properly. See: ‘npm help config’
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Administrator\AppData\Roaming\npm-cache_logs\2021-04-15T12_07_17_780Z-debug.log

Eventually switched to a different installation, typing in the command line.

cnpm install fastclick –save
Success

Vue Error: Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location

When I use the route jump, the jump does not work and the browser reports the following error.
Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: “/main”.
createRouterError vue-router.esm.js:2065
createNavigationDuplicatedError vue-router.esm.js:2035
confirmTransition vue-router.esm.js:2328
transitionTo vue-router.esm.js:2260
push vue-router.esm.js:2704
push vue-router.esm.js:3020
push vue-router.esm.js:3019
The reason for the error is that I did not add.

<router-view></router-view>

[Solution] VUE.js Load a local image with parameters in the script

Basic knowledge:
1, VUE.js When loading the local image path in the script, you need to use require, but not in the HTML tag;
2, VUE.js In principle, it is not supported to load the local image path containing parameters. Even if require is used, an error will still be reported because require.js
and
respectively 3. In many cases, we need to take data from the database and compile it, including pictures. In general, in addition to the URL of the network image and the binary image, it may also contain the local image path.

Specific operation:

<template>
  <img :src="imgA"/>
</template>

<script>
export default {
  computed: {
    the name of your function (optional parameter) {
      return require('local folder within some project (aka root)' + arguments)
    }
  },
  methods: {
    your function name2 (optional parameter2) {
      this.imgA = your function name (optional parameter)
    }
  }
}
</script>

Several key points:
1. Functions must be stored in computed, which is a dynamic calculation block. Unlike methods, require contains dynamic parameters and will not report errors;
2 2. A root directory must be provided, and the following parts can be played as you like. The root directory is necessary. During the operation, it will actually get all the files under the root directory, and then find what you need;
3. When calling, assign the function name (optional parameter) of this. You to the image path parameter (IMGA in this example).

If there is any unclear description, please leave a message.

Android realizes the fade in and fade out of animation effect

View fade animation effect

  /**
     * View fade animation effect
     */
    public  void setHideAnimation( View view, int duration)
    {
        if (null == view || duration < 0)
        {
            return;
        }

        if (null != mHideAnimation)
        {
            mHideAnimation.cancel();
        }
        // Listening for the end of animation operations
        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(duration);
        mHideAnimation.setFillAfter(true);
        view.startAnimation(mHideAnimation);
    }

View fade animation effect

/**
     * View fade animation effect
     */
    public  void setShowAnimation( View view, int duration)
    {
        if (null == view || duration < 0)
        {
            return;
        }
        if (null != mShowAnimation)
        {
            mShowAnimation.cancel();
        }
        mShowAnimation = new AlphaAnimation(0.0f, 1.0f);
        mShowAnimation.setDuration(duration);
        mShowAnimation.setFillAfter(true);
        view.startAnimation(mShowAnimation);
    }

It is best to monitor the beginning and end of the animation. For showview, call showView.setVisibility ( View.VISIBLE )Set to visible before calling showView.animate ()
for hideview, call hideView.animate (), and finally invoked in the onAnimationEnd event. hideView.setVisibility ( View.GONE ); set to invisible

Monitor processing: View fade animation effect

 /**
     * View fade animation effect
     */
    public  void setHideAnimation( final View view, int duration)
    {
        if (null == view || duration < 0)
        {
            return;
        }

        if (null != mHideAnimation)
        {
            mHideAnimation.cancel();
        }
        // Listening for the end of animation operations
        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(duration);
        mHideAnimation.setFillAfter(true);
        mHideAnimation.setAnimationListener(new AnimationListener()
        {

            @Override
            public void onAnimationStart(Animation arg0)
            {

            }

            @Override
            public void onAnimationRepeat(Animation arg0)
            {

            }

            @Override
            public void onAnimationEnd(Animation arg0)
            {
                view.setVisibility(View.GONE);
            }
        });
        view.startAnimation(mHideAnimation);
    }

Monitor processing: View fade animation effect

 /**
     * View fade animation effect
     */
    public  void setShowAnimation( final View view, int duration)
    {
        if (null == view || duration < 0)
        {
            return;
        }
        if (null != mShowAnimation)
        {
            mShowAnimation.cancel();
        }
        mShowAnimation = new AlphaAnimation(0.0f, 1.0f);
        mShowAnimation.setDuration(duration);
        mShowAnimation.setFillAfter(true);
        mShowAnimation.setAnimationListener(new AnimationListener()
        {

            @Override
            public void onAnimationStart(Animation arg0)
            {
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation arg0)
            {

            }

            @Override
            public void onAnimationEnd(Animation arg0)
            {

            }
        });
        view.startAnimation(mShowAnimation);
    }

Note: I found that after setting the view control fade, and gone (completely invisible), after these two properties. When you click the position of the control, the click event of the view will still start. However, when view gone is set separately, if you click view, there will be no response. It’s hard for me to understand. Just in the project, the click of this view needs to be processed, so when I set gone to view, I will set clickable to false again.