我是API和ES6的新手。如何发布用户名和密码,如果不正确,我将如何获得响应。顺便说一句,这个网站没有用。
fetch('http://thisissamplewebsite.com', {
method: 'post',
body: JSON.stringify({
email: document.getElementById('email').value
answer: document.getElementById('answer').value
})
});

<!DOCTYPE html>
<html>
<head>
<title>Consume API</title>
</head>
<body>
<form method="POST">
<input type="email" id="email" placeholder="email" value="aaa@yahoo.com"/>
<input type="password" id="password" placeholder="password" value="12345"/>
<input type="submit" value="Submit">
</form>
</body>
</html>
&#13;
答案 0 :(得分:1)
您的代码中有一些错误:
method
,
。但无论如何document.getElementById('answer').value
你没有回答作为其id的元素。<script>
标记。这些标记不是必需的。)查看fetch的文档以获取更多信息。 fetch on github
fetch('http://thisissamplewebsite.com', {
method: 'post',
body: JSON.stringify({
email: document.getElementById('email').value
//answer: document.getElementById('answer').value
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Consume API</title>
</head>
<body>
<form method="POST">
<input type="email" id="email" placeholder="email" value="aaa@yahoo.com"/>
<input type="password" id="password" placeholder="password" value="12345"/>
<input type="submit" value="Submit">
</form>
</body>
</html>
答案 1 :(得分:0)
服务器响应将返回response.text()
fetch('http://example.com', {
method: 'post',
body: JSON.stringify({
email: document.getElementById('email').value,
password: document.getElementById('password').value
}).then(function(response) {
alert(response.text());
//document.getElementById('answer').innerHTML = response.text();
},
function(error) {
// handle network error
})
});