Javascript常见的使用场景
一、常见语法
1. 变量声明
let
和const
(ES6+):
let count = 10; // 可变变量
const PI = 3.14; // 常量(不可重新赋值)
2. 数据类型
基本类型:
Number
, String
, Boolean
, Null
, Undefined
, Symbol
。
引用类型:
Object
, Array
, Function
, Date
。
let str = "Hello"; // string
let num = 100; // number
let isTrue = true; // boolean
let user = { name: "Tom" }; // object
let arr = [1, 2, 3]; // array
function sayHello() {} // function
3.条件语句
if (age >= 18) {console.log("成年");
} else {console.log("未成年");
}
4.循环语句
for (let i = 0; i < 5; i++) {console.log(i);
}let arr = [1, 2, 3];
arr.forEach(item => {console.log(item);
});
5. 函数
- 函数声明:
function add(a, b) {return a + b;
}
6. 对象和数组
- 对象字面量:
const user = { name: "Alice", age: 25 };
- 数组方法:
// 数组方法1:
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // [2, 4, 6]//数组方法2:
let fruits = ["apple", "banana", "orange"];fruits.push("grape"); // 添加元素
fruits.pop(); // 删除最后一个元素
fruits.indexOf("banana"); // 查找索引
fruits.slice(1, 3); // 截取子数组
fruits.map(fruit => fruit.toUpperCase()); // 映射新数组
二、常见使用场景
1. DOM操作
DOM常见操作
let element = document.getElementById("myDiv");
element.innerHTML = "新内容";
element.style.color = "red";let newParagraph = document.createElement("p");
newParagraph.textContent = "这是一个段落";
document.body.appendChild(newParagraph);
添加事件监听器:
const button = document.getElementById("myButton");
button.addEventListener("click", () => {alert("Button clicked!");
});
更新元素样式:
const element = document.querySelector(".my-class");
element.style.color = "red";
2.表单验证
校验输入字段:
const form = document.getElementById("myForm");
form.addEventListener("submit", (e) => {const input = document.getElementById("username");if (input.value.trim() === "") {e.preventDefault(); // 阻止表单提交alert("请输入用户名");}
});
3.数据处理
过滤和映射数组:
const numbers = [10, 20, 30];
const filtered = numbers.filter(n => n > 15); // [20, 30]
const mapped = numbers.map(n => n / 2); // [5, 10, 15]
合并对象:
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = { ...obj1, ...obj2 }; // { a: 1, b: 2 }
4.网络请求(AJAX)
使用
fetch
向后端请求数据:
fetch("https://api.example.com/data").then(response => response.json()).then(data => {console.log("Data received:", data);}).catch(error => {console.error("Error:", error);});
5.事件处理
监听用户交互
document.addEventListener("keydown", (e) => {if (e.key === "Enter") {console.log("Enter key pressed");}
});
6.动态加载内容
通过AJAX加载页面片段
function loadContent() {fetch("/content.html").then(response => response.text()).then(html => {document.getElementById("content").innerHTML = html;});
}
四、通过$.ajax,发送请求到后端
注意⚠️:在 JavaScript 中,使用 $.ajax 是jQuery 提供的 AJAX 方法
//1、data为formData的代码示例:
$.ajax({url: '/update_tpm_members', // 替换为你的后端接口地址type: 'POST',data: formData,processData: false, // 不处理数据contentType: false, // 不设置内容类型success: function (response) {console.log('保存成功:', response);alert(response.message);location.reload(true);},error: function (xhr, status, error) {console.error('保存失败:', error);alert(response.message);}});//2、data为json的代码示例:
$.ajax({url: "/update_tpm_members", // 请求地址type: "POST", // 请求方法data: {name: "Alice",age: 25},dataType: "json", // 预期返回 JSONcontentType: "application/json", // 发送 JSONbeforeSend: function(xhr) {xhr.setRequestHeader("Authorization", "Bearer your_token"); // 设置请求头},success: function(response) {console.log("请求成功:", response);},error: function(xhr, status, error) {console.error("请求失败:", error);},complete: function() {console.log("请求完成");}
});
2、$.ajax的参数说明:
✅ 1. 基础参数
参数名 | 类型 | 说明 |
---|---|---|
url | String | 请求的 URL 地址(必填)。 |
type | String | HTTP 请求方法(如 GET , POST , PUT , DELETE )。默认是 GET 。 |
data | Object / String | 发送到服务器的数据(键值对对象或查询字符串)。 |
dataType | String | 预期返回的数据类型(如 json , xml , html , text )。 |
✅ 2. 数据相关参数
参数名 | 类型 | 说明 |
---|---|---|
contentType | String | 发送数据到服务器时的内容类型(默认 application/x-www-form-urlencoded )。例如: application/json 表示发送 JSON 数据。 |
processData | Boolean | 是否自动将 data 对象序列化为查询字符串(默认 true )。如果发送的是 FormData 或二进制数据,需设为 false 。 |
traditional | Boolean | 是否使用传统风格的序列化方式(默认 false )。 |
✅ 3. 回调函数
参数名 | 类型 | 说明 |
---|---|---|
beforeSend | Function | 请求发送前的回调函数,可用于设置请求头或验证条件。 |
success | Function | 请求成功后的回调函数,接收服务器返回的数据。 |
error | Function | 请求失败时的回调函数,接收错误信息。 |
complete | Function | 请求完成后的回调函数(无论成功或失败都会执行)。 |
✅ 4. 高级控制
参数名 | 类型 | 说明 |
---|---|---|
async | Boolean | 是否异步请求(默认 true )。设为 false 会阻塞浏览器直到请求完成。 |
timeout | Number | 请求超时时间(单位:毫秒)。 |
cache | Boolean | 是否缓存 GET 请求结果(默认 true )。 |
global | Boolean | 是否触发全局 AJAX 事件(如 ajaxStart , ajaxStop )。 |
headers | Object | 自定义 HTTP 请求头(如 Authorization: Bearer token )。 |