方法:$.ajax();$.get();load();
前言
本文介绍JQuery中$.ajax();$.get();load();的使用方法
使用需导入JQuery,请去官网下载jQuery
JSON文件:user.json
[
{"name":"tom"},
{"name":"jerry"},
{"name":"mike"},
{"name":"admin"}
]
一、方法: ajax()
定义:
ajax() 方法用于执行 AJAX(异步 HTTP)请求。
所有的 jQuery AJAX 方法都使用 ajax() 方法。该方法通常用于其他方法不能完成的请求。
语法:
$.ajax({name:value, name:value, ... }) 注:该参数规定 AJAX 请求的一个或多个名称/值对。
参数:
contentType 发送数据到服务器时所使用的内容类型。默认是: "application/json"。
data 规定要发送到服务器的数据
dataType 预期的服务器响应的数据类型 Text json
success(result,status,xhr) 当请求成功时运行的函数 回调函数
type 规定请求的类型(GET或POST)
url 规定发送请求的URL
示例:
<script src="../js/jquery-3.6.1.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
li {
height: 40px;
line-height: 40px;
background-color: #ccc;
color: white;
}
ul {
width: 100px;
border: 1px solid #000;
background-color: pink;
}
</style>
</head>
<body>
<ul id="users"></ul>
</body>
<script>
//方法: ajax()
//通过ajax请求获取user里面的内容,然后填充到ul里面
$.ajax({
url: './json/user.json',
type: 'get',
success: function (data) {
console.log(data);
let newArr = data.map((item, index) => {
return `<li>${item.name}</li>`;
});
//放入到ul
$("#users").html(newArr.join(''));
}
})
二、方法: get()
定义:
$.get() 方法使用 HTTP GET 请求从服务器加载数据。
通过get()方法: ajax()方法的简写,此方法就是发送的get请求
语法:
$.get(URL,data,function(data,status,xhr),dataType)
示例:
<script src="../js/jquery-3.6.1.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
li {
height: 40px;
line-height: 40px;
background-color: #ccc;
color: white;
}
ul {
width: 100px;
border: 1px solid #000;
background-color: pink;
}
</style>
</head>
<body>
<ul id="users"></ul>
</body>
<script>
$.get("./json/user.json", function (data) {
let newArr = data.map((item, index) => {
return `<li>${item.name}</li>`;
});
//放入到ul
$("#users").html(newArr.join(''));
})
</script>
</html>
三、方法: load()
定义:
load() 方法从服务器加载数据,并把返回的数据放置到指定的元素中。
注意:还存在一个名为 load 的 jQuery 事件方法。调用哪个,取决于参数。
语法:
$(selector).load(url,data,function(response,status,xhr))
示例:
<script src="../js/jquery-3.6.1.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
li {
height: 40px;
line-height: 40px;
background-color: #ccc;
color: white;
}
ul {
width: 100px;
border: 1px solid #000;
background-color: pink;
}
</style>
</head>
<body>
<div class="users"></div>
</body>
<script>
//$(selector).getJSON(url,data, success(data,status ,xhr))
$("#users").load("./ data/user.json", function (data) {
console.log(JSON.parse(data));
})
</script>
以下的方法,可以直接打包表单里面的数据,转换成数组对象,
那么我们就可以通过JSON.stringify(xxx)将该数组对象转换成json字符串作为参数传递
let serArr = $("#myform").serializeArray();
console.log(serArr);
//console.log(JSON.stringify(serArr));