Ajax笔记
一、模板引擎
作用:使用模板引擎提供的模板语法,可以将数据和 HTML 拼接起来。
下载地址: https://aui.github.io/art-template/zh-cn/index.html
art-template
使用步骤:
1.下载 art-template 模板引擎库文件并在 HTML 页面中引入库文件
<script src="./js/template-web.js"></script>
- 准备 art-template 模板
<script id="tpl" type="text/html">
<div class="box"></div>
</script>
3.告诉模板引擎将哪一个模板和哪个数据进行拼接
var html = template('tpl', {username: 'zhangsan', age: '20'});
4.将拼接好的html字符串添加到页面中
document.getElementById('container').innerHTML = html;
5.通过模板语法告诉模板引擎,数据和html字符串要如何拼接
<script id="tpl" type="text/html">
<div class="box"> {{ username }} </div>
</script>
二、FormData对象
作用:
- 模拟HTML表单,相当于将HTML表单映射成表单对象,自动将表单对象中的数据拼接成请求参数的格式。
- 异步上传二进制文件
使用:
-
准备 HTML 表单
<form id="form"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="button"/> </form>
-
将 HTML 表单转化为 formData 对象
var form = document.getElementById('form'); var formData = new FormData(form);
-
提交表单对象
xhr.send(formData);
- 注意
Formdata 对象不能用于 get 请求,因为对象需要被传递到 send 方法中,而 get 请求方式的请求参数只能放在请求地址的后面。
服务器端 bodyParser 模块不能解析 formData 对象表单数据,我们需要使用 formidable 模块进行解析
实例方法
-
获取表单对象中属性の值
formData.get('key');
-
设置表单对象中属性の值
formData.set('key', 'value');
-
删除表单对象中属性の值
formData.delete('key');
-
向表单对象中追加属性值
formData.append('key', 'value');
- 注意
set 方法与 append 方法的区别是,在属性名已存在的情况下,set 会覆盖已有键名的值,append会保留两个值。
三、jQuery中的Ajax
$ajax()
发送Ajax请求
$.ajax({
type: 'get', // 请求方式
url: 'http://www.example.com', // 请求地址
data: { name: 'zhangsan', age: '20' }, // 向服务器端发送的请求参数
contentType: 'application/x-www-form-urlencoded', //格式 对象
beforeSend: function () { // 在请求发送之前调用
return false
},
success: function (response) {}, // 成功后调用的函数 形参 服务器返回的数据
error: function (xhr) {} // 失败后调用的函数 获取错误信息
});
data: 'name=zhangsan&age=20' // 字符串
contentType: 'application/json' // 传递json格式的请求参数
JSON.stringify({name: 'zhangsan', age: '20'}) // 转换
请求参数要考虑的问题
1.请求参数位置的问题
将请求参数传递到ajax函数内部,在函数内部根据请求方式的不同将请求参数放置在不同位置
get放在请求地址的后面
post放在send方法中
2.请求参数格式的问题
-
application/x-www-form-urlencoded
参数名称=参数值&参数名称=参数值
name=zhangsan&age=20
-
application/json
{name: ‘zhangsan’ , age: 20 }
1.传递对象数据类型对于函数的调用者更加友好
2.在函数内部对象数据类型转换为字符串数据类型更加方便
serialize方法
作用:将表单中的数据自动拼接成字符串类型参数
var params = $('#form').serialize();
// name=zhangsan&age=30
.get、.get、.get、post
$('#btn').on('click',function (){
// post请求
// 地址,对象,回调函数
$.get('http://www.example.com', {name: 'zhangsan', age: 30}, function (response) {
console.log(responsose) //打印形参
})
// post请求
$.get('http://www.example.com', function (response) {
console.log(responsose)
})
});