ajax get异步方法

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');
	}
	/*
	 1.缓存 在url后面连接一个随机数,时间戳
	 2.乱码 编码encodeURI
	 * */
	xhr.open('get','get.php?username='+encodeURI('刘伟')+'&age=30&t='+new Date().getTime(),true);
	//提交  发送请求
	xhr.send();
	
	//等待服务器返回内容
	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=$_GET['username'];
$age=$_GET['age'];
 
echo "你的名字:{$username},年龄:{$age}";
?>

  

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