什么是查询字符串
定义: 查询字符串(URL参数)是指在URL的末尾加上用于向服务器发送信息的字符串(变量)
格式: 将英文的'?'放在URL的末尾,然后再加上'参数=值',可以使用'&'符号进行分隔加多个参数,这个形式可以将想要发送给服务器的数据添加到URL中
//不带参数的URL地址
www.liulongbin.top:3006/api/getbooks
//带一个参数的URL地址
www.liulongbin.top:3006/api/getbooks?id=1
//带两个参数的URL地址
www.liulongbin.top:3006/api/getbooks?id=1&bookname=西游记
GET请求携带参数的本质
无论使用$.ajax(),还是使用$.get(),又或者直接使用xhr对象发起GET请求,当需要携带参数的时候,本质上都是直接将参数以查询字符串的形式,追加到URL地址的后面,发送到服务器的
$.get('url', {name: 'zs', age: 20}, function() {})
//等价于
$.get('url?name=zs&age=20', function() {})
$.ajax(method: 'GET', url: 'url', data: {name: 'zs', age: 20}, success: function() {})
//等价于
$.ajax(method: 'GET', url: 'url?name=zs&age=20', success: function() {})
代码示例:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../../js/jQuery.js"></script>
</head>
<body>
<script>
// $.get('http://www.liulongbin.top:3006/api/getbooks', {
// id: 1,
// bookname: '西游记'
// }, function(res) {
// console.log(res);
// })
$.ajax({
method: 'GET',
url: 'http://www.liulongbin.top:3006/api/getbooks',
data: {
id: 1,
bookname: '西游记'
},
success: function(res) {
console.log(res);
}
})
</script>
</body>
</html>
查询字符串是在URL中传递参数的方式,以'?'开始,用'&'分隔多个参数,如'id=1&bookname=西游记'。在JavaScript中,无论是$.get()还是$.ajax()发起GET请求,本质都是将参数转化为查询字符串附加到URL后发送到服务器。本文通过代码示例展示了如何使用jQuery进行GET请求并携带参数。

被折叠的 条评论
为什么被折叠?



