一、网络编程三大基石
1. URL与URI
```javascript
// URL示例 - 完整网络资源定位
let imageUrl = "https://www.example.com/images/photo.jpg?width=200&height=300section1";
// URI示例 - 项目内资源定位
let apiEndpoint = "/api/users/123"; // 相对于当前域名的路径
```
2. HTTP协议特性
```javascript
// HTTP请求示例
function sendHttpRequest() {
// 创建XMLHttpRequest对象
let xhr = new XMLHttpRequest();
// 配置请求 (方法, URL, 是否异步)
xhr.open('GET', 'https://api.example.com/data', true);
// 设置请求头
xhr.setRequestHeader('Content-Type', 'application/json');
// 处理响应
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
// 请求成功
console.log('响应数据:', JSON.parse(xhr.responseText));
} else {
// 请求失败
console.error('请求失败:', xhr.statusText);
}
};
// 处理错误
xhr.onerror = function() {
console.error('网络错误');
};
// 发送请求
xhr.send();
}
```
3. HTML与表单
```html
<!-- 超链接发送GET请求 -->
<a href="https://www.example.com/page?id=123" target="_blank">访问示例页面</a>
<!-- 表单发送POST请求 -->
<form action="/api/submit" method="POST">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<input type="submit" value="登录">
</form>
<!-- 使用JavaScript处理表单提交 -->
<form id="loginForm">
<input type="email" name="email" placeholder="邮箱" required>
<input type="password" name="password" placeholder="密码" required>
<button type="submit">登录</button>
</form>
<script>
document.getElementById('loginForm').addEventListener('submit', function(e) {
e.preventDefault(); // 阻止默认提交行为
// 获取表单数据
let formData = new FormData(this);
// 使用Fetch API发送请求
fetch('/api/login', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log('登录成功:', data);
})
.catch(error => {
console.error('登录失败:', error);
});
});
</script>
```
二、JavaScript核心概念
1. JavaScript简介与组成
```javascript
// ECMAScript - 语法核心
let message = "Hello, World!";
const PI = 3.14159;
// BOM - 浏览器对象模型
console.log('浏览器名称:', navigator.userAgent);
console.log('屏幕尺寸:', screen.width, 'x', screen.height);
// DOM - 文档对象模型
document.getElementById('myElement').style.color = 'red';
```
2. 输出与输入语句
```javascript
function demoOutputInput() {
// 输出语句
alert("我是警告框"); // 弹框输出
console.log("控制台输出"); // 浏览器控制台输出
console.error("错误信息"); // 错误输出
console.warn("警告信息"); // 警告输出
// 页面输出
document.write("<h1>直接写入文档</h1>");
// 指定元素输出
document.getElementById("output").innerHTML = "<strong>格式化文本</strong>";
// 输入语句
let userName = prompt("请输入您的姓名:", "张三");
let isConfirmed = confirm("确定要删除吗?");
console.log("用户输入:", userName);
console.log("用户确认:", isConfirmed);
}
```
3. 变量与数据类型
```javascript
// 变量声明
var globalVar = "我是全局变量"; // 函数作用域或全局作用域
let blockVar = "我是块级变量"; // 块级作用域
const CONSTANT_VALUE = "我是常量"; // 块级作用域,不可重新赋值
// 数据类型
let numberVar = 42; // number类型
let stringVar = "Hello"; // string类型
let booleanVar = true; // boolean类型
let nullVar = null; // null类型
let undefinedVar; // undefined类型
let objectVar = { name: "John", age: 30 }; // object类型
let arrayVar = [1, 2, 3, 4, 5]; // array类型
let dateVar = new Date(); // Date对象
// 特殊值
let notANumber = NaN; // 非数字
let infinite = Infinity; // 无穷大
// 类型检测
console.log(typeof numberVar); // "number"
console.log(typeof stringVar); // "string"
console.log(typeof nullVar); // "object" (这是JavaScript的历史遗留问题)
```
4. 类型转换
```javascript
// 转换为数值类型
console.log(parseInt("123abc")); // 123 (提取整数部分)
console.log(parseFloat("12.34abc")); // 12.34 (提取浮点数部分)
console.log(Number("123")); // 123 (整体转换)
console.log(Number("abc")); // NaN (无法转换)
// 特殊转换规则
console.log(Number(true)); // 1
console.log(Number(false)); // 0
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
// 转换为字符串
let num = 123;
console.log(num.toString()); // "123"
console.log(String(123)); // "123"
console.log(123 + ""); // "123" (隐式转换)
// 转换为布尔值
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean(1)); // true
console.log(Boolean("hello")); // true
console.log(Boolean([])); // true
console.log(Boolean({})); // true
```
5. 运算符与比较
```javascript
// 算术运算符
let a = 10, b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a b); // 30
console.log(a / b); // 3.333...
console.log(a % b); // 1
console.log(a b); // 1000 (指数运算)
// 比较运算符
console.log(5 == "5"); // true (值相等,类型不同但可转换)
console.log(5 === "5"); // false (值和类型都必须相等)
console.log(5 != "5"); // false
console.log(5 !== "5"); // true
// 逻辑运算符
console.log(true && false); // false
console.log(true || false); // true
console.log(!true); // false
// 三元运算符
let age = 20;
let status = age >= 18 ? "成人" : "未成年";
console.log(status); // "成人"
```
6. 选择与循环结构
```javascript
// if-else语句
let score = 85;
if (score >= 90) {
console.log("优秀");
} else if (score >= 80) {
console.log("良好");
} else if (score >= 60) {
console.log("及格");
} else {
console.log("不及格");
}
// switch语句
let day = 3;
switch (day) {
case 1:
console.log("星期一");
break;
case 2:
console.log("星期二");
break;
case 3:
console.log("星期三");
break;
default:
console.log("其他日子");
}
// for循环
for (let i = 1; i <= 9; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += `${j} × ${i} = ${i j}\t`;
}
console.log(row);
}
// while循环
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
// do-while循环
let j = 1;
do {
console.log(j);
j++;
} while (j <= 5);
```
7. 数组与对象
```javascript
// 数组操作
let fruits = ["Apple", "Banana", "Orange"];
fruits.push("Mango"); // 添加元素到末尾
fruits.pop(); // 移除最后一个元素
fruits.unshift("Strawberry"); // 添加元素到开头
fruits.shift(); // 移除第一个元素
// 数组遍历
fruits.forEach(function(fruit, index) {
console.log(index + ": " + fruit);
});
// 对象操作
let person = {
name: "张三",
age: 25,
job: "Developer",
sayHello: function() {
console.log("你好,我是" + this.name);
}
};
// 添加属性
person.email = "zhangsan@example.com";
// 删除属性
delete person.job;
// 遍历对象属性
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(key + ": " + person[key]);
}
}
```
8. JSON字符串转换
```javascript
// JSON字符串转对象
let jsonString = '{"empno":"1234","ename":"张三","age":"23","job":"开发"}';
// 方法1: eval() (不推荐,有安全风险)
eval("var employee = " + jsonString);
console.log(employee.ename); // 张三
// 方法2: JSON.parse() (推荐)
let employee = JSON.parse(jsonString);
console.log(employee.ename); // 张三
// 方法3: 使用jQuery (需要引入jQuery库)
// let employee = $.parseJSON(jsonString);
// 对象转JSON字符串
let newEmployee = {
empno: "5678",
ename: "李四",
age: 28,
job: "设计"
};
let jsonStr = JSON.stringify(newEmployee);
console.log(jsonStr); // {"empno":"5678","ename":"李四","age":28,"job":"设计"}
```
9. 函数定义与调用
```javascript
// 声明式函数 (会被提升)
function add(a, b) {
return a + b;
}
// 赋值式函数 (不会被提升)
let multiply = function(a, b) {
return a b;
};
// 箭头函数 (ES6)
let divide = (a, b) => a / b;
// 使用Function构造函数 (不常用)
let subtract = new Function('a', 'b', 'return a - b');
// 函数调用
console.log(add(5, 3)); // 8
console.log(multiply(5, 3)); // 15
console.log(divide(10, 2)); // 5
console.log(subtract(5, 3)); // 2
// 参数处理
function showInfo(name, age, city) {
// 参数不足时,未提供的参数值为undefined
console.log("姓名:", name);
console.log("年龄:", age);
console.log("城市:", city);
}
showInfo("张三", 25); // 城市: undefined
// 默认参数
function greet(name = "访客") {
console.log("你好, " + name);
}
greet(); // 你好, 访客
greet("李四"); // 你好, 李四
```
10. 面向对象编程
```javascript
// 封装 - 构造函数模式
function Person(id, name, age, sex) {
// 属性
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
// 方法
this.show = function() {
console.log(`身份证号: ${this.id}, 姓名: ${this.name}, 年龄: ${this.age}, 性别: ${this.sex}`);
};
}
// 创建对象实例
let p1 = new Person("1234", "张三", 23, "男");
p1.show();
// 原型继承
function Student(major, classroom) {
this.major = major;
this.classroom = classroom;
this.study = function() {
console.log(`${this.name}正在${this.classroom}学习${this.major}`);
};
}
// 设置原型链实现继承
Student.prototype = new Person("default_id", "默认姓名", 0, "未知");
// 创建学生对象
let stu1 = new Student("计算机科学", "201教室");
stu1.name = "李四";
stu1.age = 20;
stu1.show();
stu1.study();
```
11. 常用内置对象
```javascript
// Array对象
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // 5
console.log(numbers.join("-")); // "1-2-3-4-5"
console.log(numbers.slice(1, 3)); // [2, 3]
// Date对象
let now = new Date();
console.log(now.getFullYear()); // 当前年份
console.log(now.getMonth() + 1); // 当前月份 (0-11, 所以+1)
console.log(now.getDate()); // 当前日期
console.log(now.getDay()); // 星期几 (0-6, 0是周日)
// 设置日期
let specialDate = new Date();
specialDate.setFullYear(2025);
specialDate.setMonth(11); // 12月 (0-11)
specialDate.setDate(25);
console.log(specialDate.toDateString());
// Math对象
console.log(Math.PI); // 3.141592653589793
console.log(Math.round(4.7)); // 5 (四舍五入)
console.log(Math.floor(4.7)); // 4 (向下取整)
console.log(Math.ceil(4.2)); // 5 (向上取整)
console.log(Math.random()); // 0-1之间的随机数
```
12. BOM浏览器对象模型
```javascript
// 屏幕信息
function getScreenInfo() {
console.log("屏幕高度:", screen.height);
console.log("屏幕宽度:", screen.width);
console.log("可用高度:", screen.availHeight);
console.log("可用宽度:", screen.availWidth);
}
// 地址栏操作
function navigateTo(url) {
window.location.href = url;
}
function reloadPage() {
window.location.reload();
}
// 历史记录
function goBack() {
window.history.back();
}
function goForward() {
window.history.forward();
}
function goToPage(steps) {
window.history.go(steps);
}
// 弹框方法
function showDialogs() {
// 提示框
let name = prompt("请输入您的姓名:", "张三");
if (name !== null) {
// 确认框
let isConfirmed = confirm("确定您的姓名是 " + name + " 吗?");
if (isConfirmed) {
// 警告框
alert("欢迎, " + name + "!");
}
}
}
// 定时器方法
function demoTimers() {
// 一次性定时器
let timeoutId = setTimeout(function() {
console.log("3秒后执行");
}, 3000);
// 周期性定时器
let intervalId = setInterval(function() {
console.log("每秒执行一次");
}, 1000);
// 清除定时器
setTimeout(function() {
clearInterval(intervalId);
console.log("已停止周期性定时器");
}, 5000);
}
// 打开和关闭窗口
function openNewWindow() {
let newWindow = window.open("https://www.example.com", "exampleWindow", "width=600,height=400");
// 5秒后关闭窗口
setTimeout(function() {
if (newWindow && !newWindow.closed) {
newWindow.close();
}
}, 5000);
}
```
三、综合示例
表单验证示例
```html
<!DOCTYPE html>
<html>
<head>
<title>表单验证示例</title>
<style>
.error { color: red; }
.success { color: green; }
</style>
</head>
<body>
<form id="registrationForm">
<div>
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<span id="usernameError" class="error"></span>
</div>
<div>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email">
<span id="emailError" class="error"></span>
</div>
<div>
<label for="password">密码:</label>
<input type="password" id="password" name="password">
<span id="passwordError" class="error"></span>
</div>
<div>
<label for="confirmPassword">确认密码:</label>
<input type="password" id="confirmPassword" name="confirmPassword">
<span id="confirmPasswordError" class="error"></span>
</div>
<button type="submit">注册</button>
</form>
<div id="message"></div>
<script>
document.getElementById('registrationForm').addEventListener('submit', function(e) {
e.preventDefault();
// 获取表单值
let username = document.getElementById('username').value.trim();
let email = document.getElementById('email').value.trim();
let password = document.getElementById('password').value;
let confirmPassword = document.getElementById('confirmPassword').value;
// 清除之前的错误信息
clearErrors();
// 验证表单
let isValid = true;
if (username.length < 3) {
showError('usernameError', '用户名至少需要3个字符');
isValid = false;
}
if (!isValidEmail(email)) {
showError('emailError', '请输入有效的邮箱地址');
isValid = false;
}
if (password.length < 6) {
showError('passwordError', '密码至少需要6个字符');
isValid = false;
}
if (password !== confirmPassword) {
showError('confirmPasswordError', '密码不匹配');
isValid = false;
}
// 如果验证通过,提交表单
if (isValid) {
// 模拟提交成功
document.getElementById('message').className = 'success';
document.getElementById('message').textContent = '注册成功!';
// 实际应用中这里可以发送AJAX请求
// sendRegistrationData({username, email, password});
}
});
function showError(elementId, message) {
document.getElementById(elementId).textContent = message;
}
function clearErrors() {
let errorElements = document.querySelectorAll('.error');
errorElements.forEach(function(element) {
element.textContent = '';
});
document.getElementById('message').textContent = '';
document.getElementById('message').className = '';
}
function isValidEmail(email) {
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
</script>
</body>
</html>
```
总结
本文全面介绍了JavaScript的核心概念和网络编程基础知识,包括:
1. 网络编程三大基石:URL/URI、HTTP协议和HTML表单
2. JavaScript基础:变量、数据类型、运算符、流程控制
3. 函数与面向对象:函数定义、调用、封装与继承
4. 内置对象:Array、Date、Math等常用对象
5. BOM操作:浏览器窗口、历史记录、定时器等
6. 表单验证:实际应用示例
JavaScript是一门强大的脚本语言,掌握了这些基础知识后,您可以进一步学习DOM操作、事件处理、AJAX、ES6+新特性以及现代前端框架,从而开发出更加交互丰富的网页应用。

1472

被折叠的 条评论
为什么被折叠?



