请用htmlcssjs。页面里包括一个文本域输入框和一个展示框的div宽度500高度自动。写一个发送POST请求的封装的函数。函数返回值填充到展示框里
<!DOCTYPE html>
<html>
<head>
<title>POST请求封装</title>
<meta charset="utf-8">
<style>
#inputBox{
width: 500px;
height: 100px;
margin: 10px 0;
padding: 10px;
border: 1px solid #ccc;
box-sizing: border-box;
}
#resultBox{
width: 500px;
padding: 10px;
border: 1px solid #ccc;
box-sizing: border-box;
}
</style>
</head>
<body>
<textarea id="inputBox"></textarea>
<div id="resultBox"></div>
<pre><code><script>
function sendPostRequest(url, data, callback){
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
};
xhr.send(data);
}
var inputBox = document.getElementById("inputBox");
var resultBox = document.getElementById("resultBox");
inputBox.addEventListener("input", function(){
var data = "input=" + encodeURIComponent(inputBox.value);
sendPostRequest("http://example.com/api", data, function(response){
resultBox.innerHTML = response;
});
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/bgLL 著作权归作者所有。请勿转载和采集!