【问题标题】:getJSON & Bearer tokengetJSON & Bearer 令牌
【发布时间】:2019-02-18 17:07:27
【问题描述】:

我有一个有效的 getJSON 脚本来输出 JSON 字符串。 但是使用 Bearer Token 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>

【问题讨论】:

    标签: jquery json getjson bearer-token


    【解决方案1】:

    当您发出请求时,您将希望使用另一种方法将不记名令牌附加到您的标头。使用您提供的代码,它似乎不会这样做。看看 $.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>');
    });
    

    【讨论】:

    • 这很有用,我可以看到控制台日志显示数据被检索。但是在这之后如何追加表中的数据呢?
    • 当然,我会重新编辑这个答案来说明如何做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2021-07-10
    • 2016-03-23
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多