<!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>&lt;script&gt;
	function sendPostRequest(url, data, callback){
		var xhr = new XMLHttpRequest();
		xhr.open(&quot;POST&quot;, url, true);
		xhr.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) {
				callback(xhr.responseText);
			}
		};
		xhr.send(data);
	}

	var inputBox = document.getElementById(&quot;inputBox&quot;);
	var resultBox = document.getElementById(&quot;resultBox&quot;);

	inputBox.addEventListener(&quot;input&quot;, function(){
		var data = 'input=' + encodeURIComponent(inputBox.value);
		sendPostRequest('http://example.com/api', data, function(response){
			resultBox.innerHTML = response;
		});
	});
&lt;/script&gt;
</code></pre>
</body>
</html>
JavaScript POST 请求封装:发送数据并显示结果

原文地址: https://www.cveoy.top/t/topic/mIoM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录