我试图为使用API的时间表制作应用程序。现在我有了表单,可以使用用户输入字段从API获得有效的响应。现在我想将json响应保存为变量。我无法找到如何做到这一点。现在可以将json保存为var。你可以举例说明如何将整个请求作为ajax发送或找到其他方式。
这是我的html:
<!DOCTYPE html>
<html>
<head>
<title>Timetable</title>
<meta charset="utf-8">
<!-- link to css sheet -->
<link rel="stylesheet" type="text/css" href="index.css">
<!-- link to javascript -->
<script type="text/javascript" src="index.js"></script>
</head>
<header>
</header>
<body>
<!-- post action -->
<form id="auth-form" action="https://rsgdeborgen.zportal.nl/api/v3/oauth/token" method="post">
<!-- hidden input data -->
<input id="hidden-input" type="hidden" name="grant_type" value="authorization_code"/>
<!-- user inputfield || user input = 12 number long authorization code -->
<input id="user-auth-input" type="text" minlength=12 maxlength=15 required name="code" placeholder="Koppelcode"/>
<!-- post button -->
<input id="post-button" type="submit" value="inloggen"/>
</form>
<div id="return">
</div>
</body>
<footer>
</footer>
</html>
例如,json的响应是:
{"access_token":"gfb04ebuems7obhdohsvod2vdb","token_type":"bearer","expires_in":57600}
所以我想要将整个响应和“access_token”保存为变量。
发布于 2018-07-26 17:48:34
你可以在Javascript中尝试XMLHttpRequest。响应存储在响应变量中。
<script>
var response;
function sendData() {
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) {
response = xhttp.responseText;
}
}
xhttp.send(params);
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Timetable</title>
<meta charset="utf-8">
<!-- link to css sheet -->
<link rel="stylesheet" type="text/css" href="index.css">
<!-- link to javascript -->
<script type="text/javascript" src="index.js"></script>
</head>
<header>
</header>
<body>
<!-- post action -->
<form id="auth-form">
<!-- hidden input data -->
<input id="hidden-input" type="hidden" name="grant_type" value="authorization_code"/>
<!-- user inputfield || user input = 12 number long authorization code -->
<input id="user-auth-input" type="text" minlength=12 maxlength=15 required name="code" placeholder="Koppelcode"/>
<!-- post button -->
<button id="post-button" onclick="sendData()" value="inloggen">inloggens</button>
</form>
<div id="return">
</div>
</body>
<footer>
</footer>
</html>
https://stackoverflow.com/questions/-100005822
复制相似问题