jQuery手册地址:https://jquery.cuishifeng.cn/
jQuery中也封装了相关Ajax的功能
$.get()和$.post()是jQuery中最常用的Ajax方法
$.get()和$.post()请求
$.get()请求的基本使用
接收两个参数,第一个是url地址,第二个是回调函数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script src="jquery.min.js"></script> <script> $.get("test.json",function(data){ console.log("我是回调函数") }) </script> </body> </html>
也可以接收三个参数,可以将queryString的内容通过JSON添加进去
<script> $.get("test.json",{ "id":1, "name": "小明", "age": 18, "sex": "男"},function(data){ console.log("我是回调函数") }) </script>
需要注意的是,顺序不能乱,第一个参数是url地址,第二个参数是queryString的数据(JSON形式传入),第三个参数是回调函数
jQuery中如果请求了一个不存在的页面,控制台会报错,并且不会继续执行后面回调函数的内容
<script> $.get("text.json",{ "id":1, "name": "小明", "age": 18, "sex": "男"},function(data){ console.log("我是回调函数") }) </script>
请求回来的数据jQuery已经帮我们封装了数据解析,将原生的Ajax的responseText返回的字符串解析成了可读的JSON数据结构,不需要再进行eval和JSON.parse等等操作了
post请求使用方法和get请求使用方法和注意事项相同
<script> $.post("test.json",{ "id":1, "name": "小明", "age": 18, "sex": "男"},function(data){ console.log("我是回调函数") }) </script>
$.ajax()请求
$.ajax()请求的使用方法和get和post基本使用方法是相同的,将功能进行了细化
$.ajax ("test.json",{ "type": "post", "data":{ "id":1, "name": "小明", "age": 18, "sex":"男" }, "success": function (data, textStatus) { //data是后端返回的数据内容 }, "error": function (data, textStatus) { } })
- 第一个参数指的是请求的文件地址
- 第二个参数是一个JSON数据,内部又一些固定参数
- type:是请求类型
- data:当前请求携带的参数
- success: 请求成功的回调函数
- error:请求失败的回调函数