简体   繁体   English

getJSON 和不记名令牌

[英]getJSON & Bearer token

I have a working getJSON script to output the JSON strings.我有一个有效的 getJSON 脚本来输出 JSON 字符串。 But with a Bearer Token api it dosnt work.但是使用不记名令牌 api 它不起作用。

In my Http Header is allready included.. authorization: Bearer Mytoken在我的 Http Header 中已经包含.. 授权:Bearer Mytoken

does anyone have an idea for me?有人对我有什么想法吗?

    <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>

You are going to want to use another method to attach the bearer token to your headers when you make the request.当您发出请求时,您将想要使用另一种方法将不记名令牌附加到您的标头。 With the code you provided, it doesn't seem like it would do so.使用您提供的代码,它似乎不会这样做。 Look at the $.ajax method, below is an example of making a GET request.看一下 $.ajax 方法,下面是一个发起 GET 请求的例子。

You can see that you get a "done" and "fail" callback method to work with...你可以看到你得到了一个“完成”和“失败”的回调方法来处理......

$.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