《JavaScript 常用技巧》

《JavaScript 常用技巧》

1. 获取客户端 IP

let clientIp = null; $.getJSON('https://api.ipify.org?format=jsonp&callback=?', function (data) { clientIp = data.ip; });

参考:

  • https://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript
  • https://www.geeksforgeeks.org/how-to-get-client-ip-address-using-javascript/

2. 禁用 form 默认提交(避免页面刷新)

form 提交后默认会刷新页面;若只想通过 ajax 交互,用 preventDefault() 禁用默认行为:

$("#challenge-form-id").submit(function (event) { event.preventDefault(); // 在这里发起 ajax 请求 });

3. 使用原生 XMLHttpRequest 发送 GET 请求

var httpRequest = new XMLHttpRequest(); // 建立所需对象 httpRequest.open('GET', 'url', true); // 打开连接,参数写在 url 中 httpRequest.send(); // 发送请求 httpRequest.onreadystatechange = function () { if (httpRequest.readyState == 4 && httpRequest.status == 200) { var json = httpRequest.responseText; // 获取到 json 字符串,还需解析 console.log(json); } };

4. 使用原生 XMLHttpRequest 发送 POST 请求

var httpRequest = new XMLHttpRequest(); httpRequest.open('POST', 'url', true); // post 方式必须设置请求头(在建立连接后再设置) httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); httpRequest.send('name=jack&age=18'); // 请求体写在 send 中 httpRequest.onreadystatechange = function () { if (httpRequest.readyState == 4 && httpRequest.status == 200) { var json = httpRequest.responseText; // 服务端返回的数据 console.log(json); } };

5. 使用局部变量避免污染全局

凡在 function 之外的都是全局变量。将业务逻辑放进一个立即执行的匿名函数即可隔离作用域:

(function () { var privateVar = "only inside"; // 业务逻辑 })();

参考:https://stackoverflow.com/questions/5786851/define-global-variable-in-a-javascript-function

阅读 — · 全站 —
🎸 我的歌单 0 首