Ajax request
jquery ajax function
I have encapsulated an ajax function myself, the code is as follows:
var Ajax = function(url, type success, error) { $.ajax({ url: url, type: type, dataType: 'json', timeout: 10000, success: function(d) { var data = d.data; success && success(data); }, error: function(e) { error && error(e); } });};// 使用方法:Ajax('/data.json', 'get', function(data) { console.log(data);});
jsonp method
Sometimes we need to use jsonp method for cross-domain, I also encapsulated a function:
function jsonp(config) { var options = config || {}; // 需要配置url, success, time, fail四个属性 var callbackName = ('jsonp_' + Math.random()).replace(".", ""); var oHead = document.getElementsByTagName('head')[0]; var oScript = document.createElement('script'); oHead.appendChild(oScript); window[callbackName] = function(json) { //创建jsonp回调函数 oHead.removeChild(oScript); clearTimeout(oScript.timer); window[callbackName] = null; options.success && options.success(json); //先删除script标签,实际上执行的是success函数 }; oScript.src = options.url + '?' + callbackName; //发送请求 if (options.time) { //设置超时处理 oScript.timer = setTimeout(function () { window[callbackName] = null; oHead.removeChild(oScript); options.fail && options.fail({ message: "超时" }); }, options.time); }};// 使用方法:jsonp({ url: '/b.com/b.json', success: function(d){ //数据处理 }, time: 5000, fail: function(){ //错误处理 } });
Commonly used regular verification expressions
Mobile phone number verification
var validate = function(num) { var exp = /^1[3-9]\d{9}$/; return exp.test(num);};
ID card number verification
var exp = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/;
ip verification
var exp = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
Commonly used js functions
Back to top
$(window).scroll(function() { var a = $(window).scrollTop(); if(a > 100) { $('.go-top').fadeIn(); }else { $('.go-top').fadeOut(); }});$(".go-top").click(function(){ $("html,body").animate({scrollTop:"0px"},'600');});
Prevent bubbling
function stopBubble(e){ e = e || window.event; if(e.stopPropagation){ e.stopPropagation(); //W3C阻止冒泡方法 }else { e.cancelBubble = true; //IE阻止冒泡方法 } }
Replace all replaceAll
var replaceAll = function(bigStr, str1, str2) { //把bigStr中的所有str1替换为str2 var reg = new RegExp(str1, 'gm'); return bigStr.replace(reg, str2);}
Get Parameter value in browser url
var getURLParam = function(name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;};
Deep copy object
function cloneObj(obj) { var o = obj.constructor == Object ? new obj.constructor() : new obj.constructor(obj.valueOf()); for(var key in obj){ if(o[key] != obj[key] ){ if(typeof(obj[key]) == 'object' ){ o[key] = mods.cloneObj(obj[key]); }else{ o[key] = obj[key]; } } } return o;}
Array deduplication
var unique = function(arr) { var result = [], json = {}; for (var i = 0, len = arr.length; i < len; i++){ if (!json[arr[i]]) { json[arr[i]] = 1; result.push(arr[i]); //返回没被删除的元素 } } return result;};
Judge whether array elements are repeated
var isRepeat = function(arr) { //arr是否有重复元素 var hash = {}; for (var i in arr) { if (hash[arr[i]]) return true; hash[arr[i]] = true; } return false;};
Generate random numbers
function randombetween(min, max){ return min + (Math.random() * (max-min +1));}
Manipulate cookies
own.setCookie = function(cname, cvalue, exdays){ var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = 'expires='+d.toUTCString(); document.cookie = cname + '=' + cvalue + '; ' + expires;};own.getCookie = function(cname) { var name = cname + '='; var ca = document.cookie.split(';'); for(var i=0; i< ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1); if (c.indexOf(name) != -1) return c.substring(name.length, c.length); } return '';};
Summary of knowledge and skills
Data types
underfined, null, 0, false, NaN, empty string. Their logical negation results are all true.
闭包格式
好处:避免命名冲突(全局变量污染)。
(function(a, b) { console.log(a+b); //30})(10, 20);
截取和清空数组
var arr = [12, 222, 44, 88]; arr.length = 2; //截取,arr = [12, 222]; arr.length = 0; //清空,arr will be equal to [].
获取数组的最大最小值
var numbers = [5, 45822, 120, -215]; var maxInNumbers = Math.max.apply(Math, numbers); //45822 var minInNumbers = Math.min.apply(Math, numbers); //-215
浮点数计算问题
0.1 + 0.2 == 0.3 //false
为什么呢?因为0.1+0.2等于0.30000000000000004。JavaScript的数字都遵循IEEE 754标准构建,在内部都是64位浮点小数表示。可以通过使用toFixed()来解决这个问题。
数组排序sort函数
var arr = [1, 5, 6, 3]; //数字数组 arr.sort(function(a, b) { return a - b; //从小到大排 return b - a; //从大到小排 return Math.random() - 0.5; //数组洗牌 });
var arr = [{ //对象数组 num: 1, text: 'num1' }, { num: 5, text: 'num2' }, { num: 6, text: 'num3' }, { num: 3, text: 'num4' }]; arr.sort(function(a, b) { return a.num - b.num; //从小到大排 return b.num - a.num; //从大到小排 });
对象和字符串的转换
var obj = {a: 'aaa', b: 'bbb'}; var objStr = JSON.stringify(obj); // "{"a":"aaa","b":"bbb"}" var newObj = JSON.parse(objStr); // {a: "aaa", b: "bbb"}
git笔记
git使用之前的配置
1.git config --global user.email xxx@163.com 2.git config --global user.name xxx 3.ssh-keygen -t rsa -C xxx@163.com(邮箱地址) // 生成ssh 4.找到.ssh文件夹打开,使用cat id_rsa.pub //打开公钥ssh串 5.登陆github,settings - SSH keys - add ssh keys (把上面的内容全部添加进去即可)
说明:然后这个邮箱(xxxxx@gmail.com)对应的账号在github上就有权限对仓库进行操作了。可以尽情的进行下面的git命令了。
git常用命令
1、git config user.name / user.email //查看当前git的用户名称、邮箱 2、git clone https://github.com/jarson7426/javascript.git project //clone仓库到本地。 3、修改本地代码,提交到分支: git add file / git commit -m “新增文件” 4、把本地库推送到远程库: git push origin master 5、查看提交日志:git log -5 6、返回某一个版本:git reset --hard 123 7、分支:git branch / git checkout name / git checkout -b dev 8、合并name分支到当前分支:git merge name / git pull origin 9、删除本地分支:git branch -D name 10、删除远程分支: git push origin :daily/x.x.x 11、git checkout -b mydev origin/daily/1.0.0 //把远程daily分支映射到本地mydev分支进行开发 12、合并远程分支到当前分支 git pull origin daily/1.1.1 13、发布到线上: git tag publish/0.1.5 git push origin publish/0.1.5:publish/0.1.5 14、线上代码覆盖到本地: git checkout --theirs build/scripts/ddos git checkout --theirs src/app/ddos

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version