ajax用post方法传递参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS</title>
<style>
#box{
width:600px;
height:200px;
padding:20px;
border:1px solid #999;
}
</style>
</head>
<body>
<h1>ajax post方式传递参数</h1>
<hr>
Number1: <input type="text" id="num1"><br>
Number2: <input type="text" id="num2"><br>
<button onclick="loadHtml()">加载</button>
<div id="box"></div>
<script>
function loadHtml(){
//获取表单中的数据
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
//实例化XMLHttpRequest对象
if(window.XMLHttpRequest){
//非IE
var xhr = new XMLHttpRequest();
}else{
//IE 6
//var xhr = new ActiveXObject('Microsoft.XMLHTTP');
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
//给xhr绑定事件.检测请求的过程
xhr.onreadystatechange = function(){
console.log(xhr.readyState);
//如果成功接收到并响应
if(xhr.status == 200 && xhr.readyState == 4){
document.getElementById('box').innerHTML = xhr.responseText;
}
}
//进行请求的初始化
xhr.open('post','js.php',true);
//设置请求头
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
//正式发送请求
xhr.send('n1='+num1+'&n2='+num2);
}
</script>
</body>
</html>
需要了解更多web前端学习信息的同学,加群434623999