ajax登录成功后设置token
时间: 2023-08-07 08:06:45 浏览: 44
在登录成功后,可以将返回的token保存在客户端的localStorage或者sessionStorage中,以备后续请求使用。可以在ajax的success回调函数中将token保存在localStorage中,如下所示:
```
$.ajax({
url: 'your-url',
type: 'POST',
data: {
username: 'your-username',
password: 'your-password'
},
success: function(response) {
// 保存token到localStorage中
localStorage.setItem('token', response.token);
console.log('Login success!');
},
error: function(error) {
console.log(error);
}
});
```
在上面的代码中,通过localStorage.setItem()方法将返回的token保存在localStorage中,并将其设置为名为'token'的键。后续请求可以从localStorage中取出token,作为请求头的Authorization字段的值,如下所示:
```
$.ajax({
url: 'your-url',
type: 'GET',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token'),
'Content-Type': 'application/json'
},
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
```
在上面的代码中,通过localStorage.getItem()方法从localStorage中取出保存的token,将其作为请求头的Authorization字段的值。