<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ajax</title>
</head>
<body>
<span></span>
<button onclick="getInfo()">获取个人信息</button>
<!-- 1.引入jQuery文件 -->
<script type="text/javascript" src="../jquery-3.2.1.js"></script>
<script type="text/javascript">
var globalToken = "";
/*
1. var xhr = new XMLHttpRequest();
2. a.xhr.open('GET', 'http://wwww.baidu.com?key1=value1&key2=value2'); 建立连接
b.xhr.open("POST", 'http://www.baidu.com');
-- 1.application/x-www-form-urlencoded: var paramsStr = "key1=value&key2=value2"
-- 2.application/json:
var paramsObj = {key1: value1, key2:value2};
var paramsStr = JSON.stringify(paramsObj);
xhr.setRequestHeader();
xhr.setRequestHeader()
3. xhr.send(paramsStr);
4. xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var res = JSON.parse(xhr.responseText);
if (res.code == 200) {
console.log(res);
res.data.data
}
}
}
*/
// $.ajax()
$(function() {
$.ajax({
// 请求地址
url: "http://124.223.98.197:10086/prod-api/captchaImage",
// 请求方式 GET POST PUT DELETE
// type: 'GET',
data: {
key1: 1,
key2: 2
},
async: true,
success: function(res) { // data回调函数返回的结果已经是json对象
// console.log(res);
if (res.code === 200) {
$("span").text(res.uuid);
}
}
})
$.ajax({
url: "http://124.223.98.197:10086/prod-api/login",
type: "POST",
// contentType: "application/json",
headers: {
'content-type': "application/json"
},
// data的参数值:
// 如果content-type是application/json, 则需要将json对象转为json字符串
// 如果content-type是默认的application/x-www-form-urlencoded, 直接写成json对象就可以了,请求时自己会转成 'key1=value1&key2-value' 的形式
data: JSON.stringify({
// 请求所用到的参数
password: "admin123",
username: "admin"
}),
// 预期服务返回数据的类型
dataType: "json",
success: function(res) {
console.log('登录成功', res);
globalToken = res.token
},
error: function(res) {
console.log('登录失败', res);
}
})
})
function getInfo() {
$.ajax({
url: "http://124.223.98.197:10086/prod-api/getInfo",
type: "GET",
// beforeSend: function(xhr) {
// xhr.setRequestHeader('Authorization', globalToken);
// },
// 设置接口的请求超时时间, 单位是毫秒
timeout: 1000,
headers: {
'content-type': 'application/json', // 这个如果直接配置个ajax参数对象需要写成驼峰形式 contentType
'Authorization': globalToken
},
success: function(res) {
console.log('个人信息', res);
},
error: function(res) {
console.log('登录失败', res);
}
})
}
</script>
</body>
</html>
46-(JQuery的Ajax)初识Ajax
于 2023-10-26 18:08:00 首次发布