人已经过原 Danny Markov 授权翻译
在本教程中,我们将学习如何使用 JS 进行AJAX调用。
术语AJAX 表示 异步的 JavaScript 和 XML。
AJAX 在 JS 中用于发出异步网络请求来获取资源。当然,不像名称所暗示的那样,资源并不局限于XML,还用于获取JSON、HTML或纯文本等资源。
有多种方法可以发出网络请求并从服务器获取数据。我们将一一介绍。
XMLHttpRequest对象(简称XHR)在较早的时候用于从服务器异步检索数据。
之所以使用XML,是因为它首先用于检索XML数据。现在,它也可以用来检索JSON, HTML或纯文本。
function success() {
var data = JSON.parse(this.responseText)
console.log(data)
}
function error (err) {
console.log('Error Occurred:', err)
}
var xhr = new XMLHttpRequest()
xhr.onload = success
xhr.onerror = error
xhr.open("GET", ""https://jsonplaceholder.typicode.com/posts/1")
xhr.send()
我们看到,要发出一个简单的GET请求,需要两个侦听器来处理请求的成功和失败。我们还需要调用open()和send()方法。来自服务器的响应存储在responseText变量中,该变量使用JSON.parse()转换为JavaScript 对象。
function success() {
var data = JSON.parse(this.responseText);
console.log(data);
}
function error(err) {
console.log('Error Occurred :', err);
}
var xhr = new XMLHttpRequest();
xhr.onload = success;
xhr.onerror = error;
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.send(JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
);
我们看到POST请求类似于GET请求。我们需要另外使用setRequestHeader设置请求标头“Content-Type” ,并使用send方法中的JSON.stringify将JSON正文作为字符串发送。
早期的开发人员,已经使用了好多年的 XMLHttpRequest来请求数据了。现代的fetch API允许我们发出类似于XMLHttpRequest(XHR)的网络请求。主要区别在于fetch()API使用Promises,它使 API更简单,更简洁,避免了回调地狱。
Fetch 是一个用于进行AJAX调用的原生 JavaScript API,它得到了大多数浏览器的支持,现在得到了广泛的应用。
fetch(url, options)
.then(response => {
// handle response data
})
.catch(err => {
// handle errors
});
API参数
fetch() API有两个参数
API返回Promise对象
fetch() API返回一个promise对象。
错误处理
请注意,对于成功的响应,我们期望状态代码为200(正常状态),但是即使响应带有错误状态代码(例如404(未找到资源)和500(内部服务器错误)),fetch() API 的状态也是 resolved,我们需要在.then() 块中显式地处理那些。
我们可以在response 对象中看到HTTP状态:
const getTodoItem = fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.catch(err => console.error(err));
getTodoItem.then(response => console.log(response));
Response
{ userId: 1, id: 1, title: "delectus aut autem", completed: false }
在上面的代码中需要注意两件事:
错误处理
我们来看看当HTTP GET请求抛出500错误时会发生什么:
fetch('http://httpstat.us/500') // this API throw 500 error
.then(response => () => {
console.log("Inside first then block");
return response.json();
})
.then(json => console.log("Inside second then block", json))
.catch(err => console.error("Inside catch block:", err));
Inside first then block
? ? Inside catch block: SyntaxError: Unexpected token I in JSON at position 4
我们看到,即使API抛出500错误,它仍然会首先进入then()块,在该块中它无法解析错误JSON并抛出catch()块捕获的错误。
这意味着如果我们使用fetch()API,则需要像这样显式地处理此类错误:-
fetch('http://httpstat.us/500')
.then(handleErrors)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error("Inside catch block:", err));
function handleErrors(response) {
if (!response.ok) { // throw error based on custom conditions on response
throw Error(response.statusText);
}
return response;
}
? Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)
fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
body: JSON.stringify({
completed: true,
title: 'new todo item',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log(err))
Response
? {completed: true, title: "new todo item", userId: 1, id: 201}
在上面的代码中需要注意两件事:-
Axios API非常类似于fetch API,只是做了一些改进。我个人更喜欢使用Axios API而不是fetch() API,原因如下:
// 在chrome控制台中引入脚本的方法
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://unpkg.com/axios/dist/axios.min.js';
document.head.appendChild(script);
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => console.log(response.data))
.catch(err => console.error(err));
Response
{ userId: 1, id: 1, title: "delectus aut autem", completed: false }
我们可以看到,我们直接使用response获得响应数据。数据没有任何解析对象,不像fetch() API。
错误处理
axios.get('http://httpstat.us/500')
.then(response => console.log(response.data))
.catch(err => console.error("Inside catch block:", err));
Inside catch block: Error: Network Error
我们看到,500错误也被catch()块捕获,不像fetch() API,我们必须显式处理它们。
axios.post('https://jsonplaceholder.typicode.com/todos', {
completed: true,
title: 'new todo item',
userId: 1
})
.then(response => console.log(response.data))
.catch(err => console.log(err))
{completed: true, title: "new todo item", userId: 1, id: 201}
我们看到POST方法非常简短,可以直接传递请求主体参数,这与fetch()API不同。
作者:Danny Markov 译者:前端小智 来源:tutorialzine
原文:https://tutorialzine.com/2017/12-terminal-commands-every-web-developer-should-know
现代web开发中,表单是用户与网站互动的重要方式之一。HTML5为表单提交提供了强大的功能和丰富的输入类型,让收集和验证用户输入数据变得更加容易和安全。本文将详细介绍HTML5表单的各个方面,包括基本结构、输入类型、验证方法和提交过程。
HTML表单由<form>标签定义,它可以包含输入字段、标签、按钮等元素。一个基本的表单结构如下所示:
<form action="/submit_form" method="post">
<label for="name">姓名:</label>
<input type="text" id="name" name="name" required>
<label for="email">电子邮箱:</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="提交">
</form>
在这个例子中,表单有两个输入字段:姓名和电子邮箱。每个输入字段都有一个<label>标签,这不仅有助于用户理解输入的内容,也有助于屏幕阅读器等辅助技术。<form>标签的action属性定义了数据提交到服务器的URL,method属性定义了提交数据的HTTP方法(通常是post或get)。
HTML5提供了多种输入类型,以支持不同的数据格式和设备。
<!-- 单行文本 -->
<input type="text" name="username" placeholder="请输入用户名" required>
<!-- 密码 -->
<input type="password" name="password" required minlength="8">
<!-- 邮箱 -->
<input type="email" name="email" required placeholder="example@domain.com">
<!-- 搜索框 -->
<input type="search" name="search" placeholder="搜索...">
<!-- 数值 -->
<input type="number" name="age" min="18" max="100" step="1" required>
<!-- 滑动条 -->
<input type="range" name="volume" min="0" max="100" step="1">
<!-- 电话号码 -->
<input type="tel" name="phone" pattern="^\+?\d{0,13}" placeholder="+8613800000000">
<!-- 日期 -->
<input type="date" name="birthdate" required>
<!-- 时间 -->
<input type="time" name="appointmenttime">
<!-- 日期和时间 -->
<input type="datetime-local" name="appointmentdatetime">
<!-- 复选框 -->
<label><input type="checkbox" name="interest" value="coding"> 编程</label>
<label><input type="checkbox" name="interest" value="music"> 音乐</label>
<!-- 单选按钮 -->
<label><input type="radio" name="gender" value="male" required> 男性</label>
<label><input type="radio" name="gender" value="female"> 女性</label>
<!-- 下拉选择 -->
<select name="country" required>
<option value="china">中国</option>
<option value="usa">美国</option>
</select>
<!-- 颜色选择器 -->
<input type="color" name="favcolor" value="#ff0000">
<!-- 文件上传 -->
<input type="file" name="resume" accept=".pdf,.docx" multiple>
HTML5表单提供了内置的验证功能,可以在数据提交到服务器之前进行检查。
<input type="text" name="username" required>
<input type="text" name="zipcode" pattern="\d{5}(-\d{4})?" title="请输入5位数的邮政编码">
<input type="number" name="age" min="18" max="99">
<input type="text" name="username" minlength="4" maxlength="8">
当用户填写完表单并点击提交按钮时,浏览器会自动检查所有输入字段的有效性。如果所有字段都满足要求,表单数据将被发送到服务器。否则,浏览器会显示错误信息,并阻止表单提交。
<input type="submit" value="提交">
可以使用JavaScript来自定义验证或处理提交事件:
document.querySelector('form').addEventListener('submit', function(event) {
// 检查表单数据
if (!this.checkValidity()) {
event.preventDefault(); // 阻止表单提交
// 自定义错误处理
}
// 可以在这里添加额外的逻辑,比如发送数据到服务器的Ajax请求
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单提交并显示JSON</title>
</head>
<body>
<!-- 表单定义 -->
<form id="myForm">
<label for="name">姓名:</label>
<input type="text" id="name" name="name">
<br>
<label for="email">电子邮件:</label>
<input type="email" id="email" name="email">
<br>
<input type="button" value="提交" onclick="submitForm()">
</form>
<script>
// JavaScript函数,处理表单提交
function submitForm() {
// 获取表单元素
var form=document.getElementById('myForm');
// 创建一个FormData对象
var formData=new FormData(form);
// 创建一个空对象来存储表单数据
var formObject={};
// 将FormData转换为普通对象
formData.forEach(function(value, key){
formObject[key]=value;
});
// 将对象转换为JSON字符串
var jsonString=JSON.stringify(formObject);
// 弹出包含JSON字符串的对话框
alert(jsonString);
// 阻止表单的默认提交行为
return false;
}
</script>
</body>
</html>
在这个例子中:
注意,这个例子中我们使用了type="button"而不是type="submit",因为我们不希望表单有默认的提交行为。我们的JavaScript函数submitForm会处理所有的逻辑,并且通过返回false来阻止默认的表单提交。如果你想要使用type="submit",你需要在<form>标签上添加一个onsubmit="return submitForm()"属性来代替按钮上的onclick事件。
HTML5的表单功能为开发者提供了强大的工具,以便创建功能丰富、用户友好且安全的网站。通过使用HTML5的输入类型和验证方法,可以确保用户输入的数据是有效的,同时提高用户体验。随着技术的不断进步,HTML5表单和相关API将继续发展,为前端工程师提供更多的可能性。
JAX上传的用户体验更好,HTML上传用户使用更方便一点,直接在网页里面就能够操作了。示例在下面提供了,是完整的源代码,有教程,有视频教程,基本上使用非常简单,开发也非常简单,有技术支持,
网上搜了一下,基本上讲这块的文章还是很多,但是就是一个字乱,讲的很混乱。也没有提供完整的前后端示例。
用户上传的文件比较大,有20G左右,直接用HTML传的话容易失败,服务器也容易出错,需要分片,分块,分割上传。也就是将一个大的文件分成若干个小文件块来上传,另外就是需要实现秒传功能和防重复功能,秒传就是用户如果上传过这个文件,那么直接在数据库中查找记录就行了,不用再上传一次,节省时间,实现的思路是对文件做MD5计算,将MD5值保存到数据库,算法可以用MD5,或者CRC,或者SHA1,这个随便哪个算法都行。
分片还需要支持断点续传,现在HTML5虽然提供了信息记录功能,但是只支持到了会话级,也就是用户不能关闭浏览器,也不能清空缓存。但是有的政府单位上传大文件,传了一半下班了,明天继续传,电脑一关结果进度信息就丢失了,这个是他们的一个痛点。
切片的话还有一点就是在服务器上合并,一个文件的所有分片数据上传完后需要在服务器端进行合并操作。
1.下载示例
https://gitee.com/xproer/up6-vue-cli
将up6组件复制到项目中
示例中已经包含此目录
1.引入up6组件
2.配置接口地址
接口地址分别对应:文件初始化,文件数据上传,文件进度,文件上传完毕,文件删除,文件夹初始化,文件夹删除,文件列表
参考:http://www.ncmem.com/doc/view.aspx?id=e1f49f3e1d4742e19135e00bd41fa3de
3.处理事件
启动测试
启动成功
效果
数据库
*请认真填写需求信息,我们会在24小时内与您取得联系。