我知道如何将 Ajax 与 GET/POST 数据一起使用,如下代码所示,但我不知道如何将其与 Token key 一起使用(已获得 Token key)
$("#read1").click(function () {
$.support.cors = true;
$.ajax({
crossDomain: true,
url: 'http://localhost:65370/api/travels',
type: 'GET',
cache: false,
error: function (xhr, status, errorThrow) {
},
complete: function (xhr) {
},
success: function (data) {
}
});
});
$("#create1").click(function () {
var person = {
"travel_id": 4
};
$.ajax({
},
type: "post",
url: 'http://localhost:65370/api/travels',
datatype: "json",
contenttype: "application/json; charset=utf-8",
data: person,
success: function (data) {
},
error: function (xhr, status, errorThrow) {
}
});
});
我找到了以下代码的方法
//you just need to put it in Ajax content
headers:{
'Authorization': 'Bearer ' + token
}
获得令牌密钥后,您可以在“标题”中添加代码。
带有令牌的完整 JavaScript 代码
<script>
$(document).ready(function()
{
var bearer ="";
var user ={
grant_type:'password',
username:'a',
password:'a'
};
$.ajax({
type: "POST",
url: "http://localhost:50971/token",
data:user,
contentType: "application/x-www-form-urlencoded",
dataType: "json",
success: function (data) {
bearer = JSON.parse(JSON.stringify(data));
bearer = bearer.access_token;
Authorization();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
function Authorization() {
$.ajax({
type: "GET",
url: "http://localhost:50971/api/employee/GetEmployees",
headers: {
'Authorization': 'Bearer ' + bearer
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (a) {
alert(JSON.stringify(a))
//$.each(a, function (x, y) {
// alert(x)
// alert(y)
// $.each(y, function (x, y) {
// alert(x)
// alert(y)
// });
//});
//alert("Hello: " + a.Name + ".\nCurrent Date and Time: " + a.address);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
})
</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)