当前位置: 首页 > wzjs >正文

网站建设怎么做分录aso优化是什么意思

网站建设怎么做分录,aso优化是什么意思,新乡网站自然优化,网站建设合同内容Ajax与Node.js Web服务器开发全面指南 一、初识Ajax 1.1 Ajax基本概念 语法知识点: Ajax (Asynchronous JavaScript and XML) 是一种无需重新加载整个网页的情况下,能够更新部分网页的技术核心对象:XMLHttpRequest工作原理: 创…

Ajax与Node.js Web服务器开发全面指南

一、初识Ajax

1.1 Ajax基本概念

语法知识点:

  • Ajax (Asynchronous JavaScript and XML) 是一种无需重新加载整个网页的情况下,能够更新部分网页的技术
  • 核心对象:XMLHttpRequest
  • 工作原理:
    1. 创建XMLHttpRequest对象
    2. 配置请求方法和URL
    3. 发送请求
    4. 处理服务器响应

基础语法:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'url', true); // true表示异步
xhr.send();
xhr.onreadystatechange = function() {if(xhr.readyState === 4 && xhr.status === 200) {console.log(xhr.responseText);}
};

1.2 Ajax完整案例

<!DOCTYPE html>
<html>
<head><title>Ajax基础示例</title>
</head>
<body><button id="loadData">加载数据</button><div id="content"></div><script>document.getElementById('loadData').addEventListener('click', function() {// 1. 创建XHR对象const xhr = new XMLHttpRequest();// 2. 配置请求xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);// 3. 设置响应类型为JSONxhr.responseType = 'json';// 4. 发送请求xhr.send();// 5. 处理响应xhr.onload = function() {if (xhr.status === 200) {const data = xhr.response;document.getElementById('content').innerHTML = `<h3>${data.title}</h3><p>${data.body}</p>`;} else {console.error('请求失败:', xhr.status);}};// 6. 错误处理xhr.onerror = function() {console.error('请求出错');};});</script>
</body>
</html>

二、Web服务器搭建

2.1 Web服务器基本概念

语法知识点:

  • Web服务器是处理HTTP请求并返回响应的软件
  • 主要功能:
    • 监听端口
    • 接收请求
    • 处理请求
    • 返回响应
  • 常见Web服务器:Apache、Nginx、Node.js等

三、安装Node.js

3.1 安装步骤

  1. Windows/macOS

    • 官网下载安装包:https://nodejs.org/
    • 运行安装程序
    • 验证安装:node -vnpm -v
  2. Linux

    # 使用nvm安装(推荐)
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
    nvm install --lts
    

四、创建Node.js应用

4.1 初始化项目

mkdir my-node-app
cd my-node-app
npm init -y

4.2 基础HTTP服务器

语法知识点:

  • Node.js内置http模块
  • createServer()方法创建服务器
  • listen()方法启动服务器
  • 请求对象(req)和响应对象(res)

案例代码:

// 引入http模块
const http = require('http');// 创建HTTP服务器
const server = http.createServer((req, res) => {// 设置响应头res.writeHead(200, {'Content-Type': 'text/plain'});// 根据URL路径返回不同响应if (req.url === '/') {res.end('欢迎来到首页\n');} else if (req.url === '/about') {res.end('关于我们\n');} else {res.writeHead(404, {'Content-Type': 'text/plain'});res.end('页面未找到\n');}
});// 监听3000端口
server.listen(3000, () => {console.log('服务器运行在 http://localhost:3000/');
});

五、运行Web服务

5.1 启动服务器

node server.js

5.2 使用nodemon自动重启

npm install -g nodemon
nodemon server.js

六、访问Web服务

6.1 浏览器访问

直接在浏览器地址栏输入:http://localhost:3000

6.2 使用curl测试

curl http://localhost:3000
curl http://localhost:3000/about

七、完整案例:Node.js + Ajax交互

7.1 服务器端代码

// server.js
const http = require('http');
const url = require('url');
const querystring = require('querystring');// 模拟数据库
let users = [{ id: 1, name: '张三', age: 25 },{ id: 2, name: '李四', age: 30 }
];const server = http.createServer((req, res) => {const parsedUrl = url.parse(req.url);const path = parsedUrl.pathname;const query = querystring.parse(parsedUrl.query);// 设置CORS头res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');res.setHeader('Access-Control-Allow-Headers', 'Content-Type');// 处理预检请求if (req.method === 'OPTIONS') {res.writeHead(204);res.end();return;}// 路由处理if (path === '/api/users' && req.method === 'GET') {// 获取用户列表res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(users));} else if (path === '/api/users' && req.method === 'POST') {// 添加新用户let body = '';req.on('data', chunk => {body += chunk.toString();});req.on('end', () => {const newUser = JSON.parse(body);newUser.id = users.length + 1;users.push(newUser);res.writeHead(201, { 'Content-Type': 'application/json' });res.end(JSON.stringify(newUser));});} else {res.writeHead(404, { 'Content-Type': 'text/plain' });res.end('Not Found');}
});server.listen(3000, () => {console.log('API服务器运行在 http://localhost:3000');
});

7.2 客户端代码

<!DOCTYPE html>
<html>
<head><title>Node.js + Ajax 示例</title><style>table { border-collapse: collapse; width: 100%; }th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }th { background-color: #f2f2f2; }form { margin: 20px 0; padding: 20px; border: 1px solid #ddd; }input { margin: 5px 0; display: block; }</style>
</head>
<body><h1>用户管理系统</h1><h2>添加用户</h2><form id="userForm"><input type="text" id="name" placeholder="姓名" required><input type="number" id="age" placeholder="年龄" required><button type="submit">添加</button></form><h2>用户列表</h2><table id="userTable"><thead><tr><th>ID</th><th>姓名</th><th>年龄</th></tr></thead><tbody></tbody></table><script>// 获取DOM元素const userForm = document.getElementById('userForm');const userTable = document.getElementById('userTable').querySelector('tbody');// 加载用户列表function loadUsers() {const xhr = new XMLHttpRequest();xhr.open('GET', 'http://localhost:3000/api/users', true);xhr.onload = function() {if (xhr.status === 200) {const users = JSON.parse(xhr.responseText);renderUsers(users);} else {console.error('加载用户失败:', xhr.status);}};xhr.onerror = function() {console.error('请求出错');};xhr.send();}// 渲染用户列表function renderUsers(users) {userTable.innerHTML = '';users.forEach(user => {const row = document.createElement('tr');row.innerHTML = `<td>${user.id}</td><td>${user.name}</td><td>${user.age}</td>`;userTable.appendChild(row);});}// 添加新用户userForm.addEventListener('submit', function(e) {e.preventDefault();const name = document.getElementById('name').value;const age = document.getElementById('age').value;const xhr = new XMLHttpRequest();xhr.open('POST', 'http://localhost:3000/api/users', true);xhr.setRequestHeader('Content-Type', 'application/json');xhr.onload = function() {if (xhr.status === 201) {loadUsers(); // 刷新列表userForm.reset(); // 重置表单} else {console.error('添加用户失败:', xhr.status);}};xhr.onerror = function() {console.error('请求出错');};xhr.send(JSON.stringify({ name, age: parseInt(age) }));});// 初始加载用户列表loadUsers();</script>
</body>
</html>

八、关键语法点详解

8.1 XMLHttpRequest对象方法

方法描述
open(method, url, async)初始化请求
send([body])发送请求
setRequestHeader(header, value)设置请求头
abort()取消请求

8.2 XMLHttpRequest对象属性

属性描述
readyState请求状态 (0-4)
statusHTTP状态码
statusText状态文本
response响应体
responseText响应文本
responseType响应类型
timeout超时时间

8.3 Node.js HTTP模块核心API

方法/属性描述
http.createServer([options][, requestListener])创建HTTP服务器
server.listen(port[, host][, backlog][, callback])启动服务器
request.method请求方法
request.url请求URL
response.writeHead(statusCode[, statusMessage][, headers])写入响应头
response.write(chunk[, encoding][, callback])写入响应体
response.end([data][, encoding][, callback])结束响应

九、进阶主题

9.1 Fetch API替代XHR

// 使用Fetch API重写加载用户函数
async function loadUsers() {try {const response = await fetch('http://localhost:3000/api/users');if (!response.ok) throw new Error('Network response was not ok');const users = await response.json();renderUsers(users);} catch (error) {console.error('加载用户失败:', error);}
}

9.2 使用Express框架简化服务器开发

npm install express
const express = require('express');
const app = express();app.use(express.json());app.get('/api/users', (req, res) => {res.json(users);
});app.post('/api/users', (req, res) => {const newUser = req.body;newUser.id = users.length + 1;users.push(newUser);res.status(201).json(newUser);
});app.listen(3000, () => {console.log('Express服务器运行在 http://localhost:3000');
});

通过以上内容,您已经掌握了从Ajax基础到Node.js Web服务器开发的完整知识体系,包括核心语法、实际案例和进阶技巧。这些知识将为您的前后端分离开发打下坚实基础。

http://www.dtcms.com/wzjs/168760.html

相关文章:

  • 网站怎么做架构图小程序制作
  • 网站如何管理站长工具樱花
  • 网站改版 影响google 404跳首页百度移动排名优化软件
  • 八年级信息技术网站建立怎么做怎么让百度快速收录网站
  • 莆田外贸自建网站环球网今日疫情消息
  • wordpress调用第一张图片不显示搜狗优化排名
  • 做毕业证教育网站超级软文
  • 最新台湾消息台湾新闻百度关键词搜索优化
  • 美食网站建设的背景和目的百度竞价广告收费标准
  • 做盗版视频网站成本多少钱抖音关键词排名
  • 哪个网站可以做中国代购百度收录网址
  • 济源网站维护传统营销和网络营销的区别
  • 网站建设费用分录1688精品货源网站入口
  • 沈阳网站建设58同城怎么交换友情链接
  • 网站建设与什么专业有关优秀网站网页设计分析
  • 星沙网站制作哪个浏览器看黄页最快夸克浏览器
  • 网站数据没有更新小白如何学电商运营
  • 盛泽做网站的深圳网站seo
  • app网站如何做推广精准客户信息一条多少钱
  • 潍坊做网站的企业网上做推广怎么收费
  • 做彩票网站代理违法吗以网红引流促业态提升
  • 四川移动网站建设报价seo外包 杭州
  • 沭阳网站建设招聘百度seo培训
  • 照片做视频的软件 模板下载网站优化大师官方免费下载
  • 相册管理网站模板下载长沙市最新疫情
  • 怎么做免费网站推广网站seo平台
  • 做婚庆的网站百度手机网页
  • 做细分行业信息网站上海关键词优化方法
  • 网站开发常用语言网上做推广怎么收费
  • 软件开发公司哪家好郑州seo技术代理