【问题标题】:How do i send this form and store the JSON as a var我如何发送此表单并将 JSON 存储为 var
【发布时间】:2018-07-18 18:07:20
【问题描述】:

我想在用户输入授权码后将此表单发送到 API。我知道我需要用 JS 拦截提交或将表单作为 AJAX 帖子发送。我已经将我的尝试包括在内,但我无法让它们工作。响应如下所示:

{"access_token":"mfi2s6i41i8hannfkaa3l87rbt","token_type":"bearer","expires_in":57600}

我想将响应保存为 3 个单独的 var,但对于大多数 access_token

html:

  <body>
    <!--   form for authentication   -->
    <form id="auth-form" action="https://rsgdeborgen.zportal.nl/api/v3/oauth/token" method="post">
    <!--   hidden post data      -->
    <input id="hidden-input" type="hidden" name="grant_type" value="authorization_code"/>
    <!--    user inputfield || user input = 12 number long authorization code from: https://rsgdeborgen.zportal.nl -->
    <input id="user-auth-input" name="code" type="text" placeholder="Koppelcode" minlength=12 maxlength=15 required autofocus/>
    <!--    post button    -->
    <button id="post-button" value="inloggen" onclick="change()">inloggen</button>
  </form>
  <div id="display">
    
  </div>
  <!--   link to javascript   -->
  <script type="text/javascript" src="index.js"></script>
</body>

尝试 AJAX

function sendData(callback) 
{
    var xhttp = new XMLHttpRequest();
    var url = 'https://rsgdeborgen.zportal.nl/api/v3/oauth/token';
    var params = 'code=' + document.getElementById('user-auth-input').value;
    xhttp.open('POST', url, true);

    xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    xhttp.onreadystatechange = function () 
    {
        if (xhttp.readyState == 4 && xhttp.status == 200) 
        {
            var response = xhttp.responseText, js;
            try
            {
              js = JSON.parse(response);
              if(typeof callback === 'function') callback(js);
            }
            catch (e)
            {
              if(typeof callback === 'function') callback(null);
            }
        }
    }
    xhttp.send(params);
}

function useToken(obj)
{
  if(obj) console.log("Token = " + obj.access_token);
}

sendData(useToken);

link to codepen

【问题讨论】:

    标签: javascript html json ajax api


    【解决方案1】:

    服务器响应代码 500,因为缺少 grant_type

    【讨论】:

    • 感谢回复,我试过这样: var body = { grant_type: 'authorization-code';授权码:document.getElementById("user-auth-input"); }; $.ajax({ url: 'rsgeborgen.zportal.nl/api/v3/oauth/token', type: 'POST', dataType: 'json', data: body, complete: function(result) { //完成时调用 alert(result); }, 成功: function(result) { //成功时调用 alert(result); }, error: function(result) { alert(result); }, });
    • HTML ^^
    猜你喜欢
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2018-08-18
    相关资源
    最近更新 更多