繁体   English   中英

getJSON 和不记名令牌

[英]getJSON & Bearer token

我有一个有效的 getJSON 脚本来输出 JSON 字符串。 但是使用不记名令牌 api 它不起作用。

在我的 Http Header 中已经包含.. 授权:Bearer Mytoken

有人对我有什么想法吗?

    <div id = "stage" style = "background-color:#cc0;">
         STAGE
      </div>

      <input type = "button" id = "driver" value = "Load Data" />

<script>
         $(document).ready(function() {

            $("#driver").click(function(event){
               $.getJSON('https://www.myapiwithbtoken.com/result.json', function(jd) {
                  $('#stage').html('<p> Name: ' + jd.name + '</p>');
                  $('#stage').append('<p>Age : ' + jd.age+ '</p>');
                  $('#stage').append('<p> M: ' + jd.m+ '</p>');
               });
            });

         });
      </script>

当您发出请求时,您将想要使用另一种方法将不记名令牌附加到您的标头。 使用您提供的代码,它似乎不会这样做。 看一下 $.ajax 方法,下面是一个发起 GET 请求的例子。

你可以看到你得到了一个“完成”和“失败”的回调方法来处理......

$.ajax({
    type: "GET", //GET, POST, PUT
    url: '/authenticatedService'  //the url to call
    contentType: contentType,           
    beforeSend: function (xhr) {   //Set token here
        xhr.setRequestHeader("Authorization", 'Bearer '+ token);
    }
}).done(function (response) {
    //Response ok. Work with the data returned
         $('#stage').html('<p> Name: ' + response.name + '</p>');
         $('#stage').append('<p>Age : ' + response.age+ '</p>');
         $('#stage').append('<p> M: ' + response.m+ '</p>');

}).fail(function (err)  {
    //Handle errors here
         $('#stage').append('<p>error with fetching results</p>');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM