ajax异步post方法

HTML

<input type="button" name="btn" id="btn" value="按钮" />

JS

var oBtn=document.getElementById("btn");

oBtn.onclick=function(){
	var xhr=null;
	try{
		xhr=new XMLHttpRequest();
	}catch(e){
		xhr=new ActiveXObject('Microsoft.XMLHTTP');
	}
	/*
	 post方式,数据放在send()里面作为参数传递
	 post方式没有缓存问题
	 post方式无需编码
	 * */
	xhr.open('post','post.php',true);
	//申明发送的数据类型
	xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
	//提交  发送请求
	xhr.send('username=刘伟&age=30');
	
	//等待服务器返回内容
	xhr.onreadystatechange=function(){
		if(xhr.readyState==4){
			if(xhr.status==200){
				alert(xhr.responseText);
			}else{
				alert('出错了,Err'+xhr.status);
			}
			
		}
	}
}

PHP

<?php
header('content-type:text/html;charset="utf-8"');
error_reporting(0);
 
$username=$_POST['username'];
$age=$_POST['age'];
 
echo "你的名字:{$username},年龄:{$age}";
?>

  

原文地址:https://www.cnblogs.com/yangxue72/p/8241632.html