如何发送此表单并将JSON存储为变量

时间:2018-07-18 18:07:21

标签: javascript html json ajax api

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

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

我想将响应另存为3个独立变量,但对于大多数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

1 个答案:

答案 0 :(得分:0)

由于缺少grant_type,服务器以代码500响应。