1.0 网页中如何请求数据
- var xhrObj = new XMLHttpRequest()
2.0 jQuery 中发起 Ajax
- $.get()
- $.post()
- $.ajax()
3.0 $.get()函数的语法
语法:
$.get(url,[data],[callback])
url 要请求的地址, data 请求资源期间要携带的参数 , callback 请求成功后的回调函数
1.发起不带参数的GET请求 (这个是获取所有的数据)
$(function () {
$('#btnGET').on('click', function () {
$.get('http://www.liulongbin.top:3006/api/getbooks', function (res) {
console.log(res)
})
})
})
2.发起带参数的GET请求 (这个表示是请求获取 id:1 的这个数据)
$(function () {
$('#btnGETINFO').on('click', function () {
$.get('http://www.liulongbin.top:3006/api/getbooks', { id: 1 }, function (res) {
console.log(res)
})
})
})
4.0 $.post()函数的语法
语法:
$.post(url, [data], [callback])
url 提交数据的地址, data 要提交的数据 , callback 数据提交成功后的回调函数
$(function () { (提交 data里的数据)
$('#btnPOST').on('click', function () {
$.post('http://www.liulongbin.top:3006/api/addbook', { bookname: '水浒传', author: '施耐庵', publisher: '天津图书出版社' }, function (res) {
console.log(res)
})
})
})
5.0 $.ajax()函数的语法
$.ajax() 函数的基本语法如下:
1. 发起 get 请求
$(function() {
$('#btnGET').on('click', function() {
$.ajax({
type: 'GET',
url: 'http://www.liulongbin.top:3006/api/getbooks',
data: { // 可以不写 就是获取所有的数据
id: 1
},
success: function(res) {
console.log(res)
}
})
})
})
2. 发起 post 请求
$(function () {
$('#btnPOST').on('click', function () {
$.ajax({
type: 'POST',
url: 'http://www.liulongbin.top:3006/api/addbook',
data: {
bookname: '史记',
author: '司马迁',
publisher: '上海图书出版社'
},
success: function (res) {
console.log(res)
}
})
})
})
----------------------------------------------------------------------------------
通过Ajax提交表单数据
1.0 form表单标签的属性
-
action(值是url地址,规定提交表单时向何处发送表单数据)
当 表单在 未指定 action 属性值的情况下,action 的 默认值 为当前页面的 URL 地址 -
method(get或post,规定以何种方式把表单数据提交到 action URL)
默认情况下,method 的值为 get,表示通过URL地址的形式,把表单数据提交到 action URL。 -
enctype (规定在发送表单数据之前如何对其进行编码)
application/x-www-form-urlencoded(在发送前编码所有字符(默认))、
multipart/form-data(不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。)
text/plain(空格转换为 “+” 加号,但不对特殊字符编码。(很少用)) -
target (规定在何处打开 action URL)
_blank (在新窗口中打开。)
_self (默认。在相同的框架中打开。)
_parent (在父框架集中打开。很少用)
_top (在整个窗口中打开。很少用)
framename (在指定的框架中打开。很少用)
2.0 监听表单提交事件
- submit 提交事件
$('#f1').on('submit', function() {
alert('监听到了表单的提交事件2')
})
2.1 阻止表单默认提交行为
- e.preventDefault()
$('#f1').on('submit', function(e) {
alert('监听到了表单的提交事件2')
阻止表单的提交和页面的跳转
e.preventDefault();
})
2.2 快速获取表单中的数据
- serialize()函数 (可以一次性获取到表单中的所有的数据。)
$('#f1').on('submit', function(e) {
alert('监听到了表单的提交事件2')
e.preventDefault();
$('#f1').serialize();
(注意:在使用 serialize() 函数快速获取表单数据时,必须为每个表单元素添加 name 属性!)
})
----------------------------------------------------------------------------------
模板引擎
使用步骤:
- 导入 art-template
- 定义数据
- 定义模板
- 调用 template 函数
- 渲染HTML结构
1.0 art-template标准语法
- 在 {{ }} 内可以进行变量输出,或循环数组等操作。
2.0 art-template标准语法 - 输出 以及 案例
在 {{ }} 语法中,可以进行变量的输出、对象属性的输出、三元表达式输出、逻辑或输出、加减乘除等表达式输出。
{{value}} 1. 变量的输出
{{obj.key}} 2. 对象属性的输出
{{obj['key']}} 3. 对象属性的输出
{{a ? b : c}} 4. 三元表达式输出
{{a || b}} 5. 逻辑或输出
{{a + b}} 6. 加减乘除
- {{@ test}} (原文输出)
- {{if v1}} 按需输出的内容 {{else if v2}} 按需输出的内容 {{/if}} (条件输出)
- {{each arr}} (循环输出)
{{/each}} (索引为 {{$ index}},内容为{{$ value}},$后面没有空格) - {{value | filterName}} (过滤器(类似回调函数))
template.defaults.imports.filterName = function(value){/return处理的结果/}
(前面三个英文是固定的,第四个是函数名)
3.0 正则与字符串操作----基本语法
- exec() 函数用于检索字符串中的正则表达式的匹配。
var str = 'hello'
var pattern = /o/
// 检测 str 里面有没有 o 如果有 返回该匹配值(hello等)
var result = pattern.exec(str)
console.log(result)
// 输出的结果["o", index: 4, input: "hello", groups: undefined]
3.1 正则与字符串操作----分组
var str = '<div>我是{{name}}</div>'
var pattern = /{{([a-zA-Z]+)}}/
var result = pattern.exec(str)
console.log(result)
// 得到 name 相关的分组信息
// ["{{name}}", "name", index: 7, input: "<div>我是{{name}}</div>", groups: undefined]
3.2 正则与字符串操作----字符串的replace函数
- replace() 函数用于在字符串中用一些字符替换另一些字符
4.0 实现简易的模板引擎
实现步骤:
- 定义模板结构
- 预调用模板引擎
- 封装 template 函数
- 导入并使用自定义的模板引擎
----------------------------------------------------------------------------------
XMLHttpRequest的基本使用
1.1 使用xhr发起GET请求(带参数的get请求(后面加 ?+参数))
<script>
// 1. 创建 XHR 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
//带参数的get请求
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
// 3. 调用 send 函数
xhr.send()
// 4. 监听 onreadystatechange 事件
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 获取服务器响应的数据
console.log(xhr.responseText)
}
}
var xhr = new XMLHttpRequest();
</script>
1.2 使用xhr发起POST请求
// 1. 创建 xhr 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数
xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')
// 3. 设置 Content-Type 属性
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 4. 调用 send 函数
xhr.send('bookname=水浒传&author=施耐庵&publisher=上海图书出版社')
// 5. 监听事件
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
1.3 xhr对象的readyState属性
if (xhr.readyState === 4 && xhr.status === 200) {
// 获取服务器响应的数据
console.log(xhr.responseText)
}
状态: 描述:
readyState === 0 (UNSENT) XMLHttpRequest 对象已被创建,但尚未调用 open方法。
readyState === 1 (OPENED) open() 方法已经被调用。
readyState === 2 (HEADERS_RECEIVED) send() 方法已经被调用,响应头也已经被接收。
readyState === 3 (LOADING) 数据接收中,此时 response 属性中已经包含部分数据。
readyState === 4 (DONE) Ajax 请求完成,这意味着数据传输已经彻底完成或失败。
1.4 JSON 的数组结构和对象结构
必须是使用英文的 双引号 包裹的字符串
[ "java", "python", "php" ]
[ 100, 200, 300.5 ]
[ true, false, null ]
[ { "name": "zs", "age": 20}, { "name": "ls", "age": 30} ]
[ [ "苹果", "榴莲", "椰子" ], [ 4, 50, 5 ] ]
1.5 JSON和JS对象的关系以及互相转换
- JSON.parse() 从 JSON 字符串转换为 JS 对象
- JSON.stringify() 从 JS 对象转换为 JSON 字符串
1.6 封装自己的Ajax函数
2.0 XMLHttpRequest Level2的新特性
- xhr.timeout = 3000 (设置 HTTP 请求的时限)
- xhr.ontimeout = function(){} (超时后的回调函数)
// 设置 超时时间
xhr.timeout = 300
// 设置超时以后的处理函数
xhr.ontimeout = function () {
console.log('请求超时了!')
}
2.1 FormData对象管理表单数据
- FormData对象的基本使用
// 1. 创建 FormData 实例
var fd = new FormData()
// 2. 调用 append 函数,向 fd 中追加数据
fd.append('uname', 'zs')
fd.append('upwd', '123456')
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')
xhr.send(fd) // 3. 调用
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
}
}
- 使用FormData快速获取表单中的数据
// 1. 通过 DOM 操作,获取到 form 表单元素
var form = document.querySelector('#form1')
form.addEventListener('submit', function(e) {
// 阻止表单的默认提交行为
e.preventDefault()
// 创建 FormData,快速获取到 form 表单中的数据
var fd = new FormData(form)
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')
xhr.send(fd) // 调用
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
}
}
})
2.2 上传文件
- var files = document.querySelector(’#file1’).files
2.3 显示文件上传进度
- xhr.upload.onprogress 事件 (获取到文件的上传进度)
3.0 jQuery高级用法
- jQuery实现文件上传
- ajaxStart(callback) (Ajax 请求 开始 时,执行 ajaxStart 函数。)
- ajaxStop(callback) (Ajax 请求 开始 时,执行 ajaxStart 函数。)
$(function() {
// 监听到Ajax请求被发起了
$(document).ajaxStart(function() {
$('#loading').show()
})
// 监听到 Ajax 完成的事件
$(document).ajaxStop(function() {
$('#loading').hide()
})
$('#btnUpload').on('click', function() {
// 1. 将 jQuery 对象转化为 DOM 对象,并获取选中的文件列表
var files = $('#file1')[0].files // 后面的files属性 就是获取选中的文件列表
// 2. 判断是否选择了文件
if (files.length <= 0) {
return alert('请选择文件后再上传!')
}
// 3. 向 FormData 中追加文件
var fd = new FormData()
fd.append('avatar', files[0])
// 发起 jQuery 的 Ajax 请求,上传文件 (只要调用 ajax 才能上传文件 而不是 get 或 post)
$.ajax({
method: 'POST',
url: 'http://www.liulongbin.top:3006/api/upload/avatar',
data: fd,
// 下面两个是固定写法 必须要有
// 不修改 Content-Type 属性,使用 FormData 默认的 Content-Type 值
processData: false,
// 不对 FormData 中的数据进行 url 编码,而是将 FormData 数据原样发送到服务器
contentType: false,
success: function(res) {
console.log(res)
}
})
})
})
3.1 axios网络数据请求库
- axios 发起 get 请求的语法:
- axios发起POST请求
- 直接使用axios发起请求
----------------------------------------------------------------------------------
跨域
1.0 JSONP 来进行跨域
1. 定义一个 success 回调函数:
<script>
function success(data) {
console.log('获取到了data数据:')
console.log(data)
}
</script>
2. 通过 <script> 标签,请求接口数据:
<script src="http://ajax.frontend.itheima.net:3006/api/jsonp?callback=success&name=zs&age=20"></script>
2.0 jQuery中的JSONP
<script>
$(function() {
// 发起JSONP的请求
$.ajax({
url: 'http://ajax.frontend.itheima.net:3006/api/jsonp?name=zs&age=20',
// 代表我们要发起JSONP的数据请求
dataType: 'jsonp',
jsonp: 'callback', // 发送到服务端的参数名称, 默认为 callback
jsonpCallback: 'abc', // 自定义函数名 默认为 jQuery..........
success: function(res) {
console.log(res)
}
})
})
</script>