我知道如何将 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
}
获得 token key 后,您可以在“标题”中添加代码。
带有 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>
关于javascript - 如何使用 GET/POST 和 Token key 基于 Ajax 调用 ASP.NET Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37608965/