JavaScript POST 请求封装:发送数据并显示结果
<!DOCTYPE html>
<html>
<head>
<title>JavaScript 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/mIoM 著作权归作者所有。请勿转载和采集!