2017-07-27 21 views
-3

我對API和ES6很陌生。我將如何發佈用戶名和密碼,並在不正確的情況下獲得回覆。順便說一句,這個網站不工作。 如何使用ES6獲取API

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="[email protected]"/> 
 
<input type="password" id="password" placeholder="password" value="12345"/> 
 
<input type="submit" value="Submit"> 
 
</form> 
 

 

 
</body> 
 
</html>

+0

你在你的HTML代碼 – Colin

+0

拼寫錯誤的方法,他們有取一個非常好的文檔。看這裏https://github.github.io/fetch/ – Colin

+0

@Colin。你能幫我構造這個代碼嗎? – Joseph

回答

1

你在你的代碼的一些錯誤:

  1. 你在你的HTML表單
  2. 你傳入一個無效的JSON對象拼錯method。你錯過了兩個物體之間的一個,。但無論如何document.getElementById('answer').value你沒有答案的元素作爲它的ID。
  3. (您剪斷不會工作,因爲你不包括獲取庫)
  4. (除去在JS地區的<script>標籤在你的片段。他們沒有必要)
  5. 的片段也將無法正常工作,因爲API網址不響應。

查看獲取更多信息的文件。 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="[email protected]"/> 
 
<input type="password" id="password" placeholder="password" value="12345"/> 
 
<input type="submit" value="Submit"> 
 
</form> 
 

 

 
</body> 
 
</html>

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 
    }) 
}); 
+0

你的代碼不會工作,因爲你試圖把'JSON.stringify()'函數放在後面的部分。它必須在'fetch()'函數之後。 – Colin