<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
<script>
window.onload = function () {
var
oSend = document.getElementById('send');
oSend.onclick = function () {
var xmlHttp = null;
if(window.ActiveXObject){
xmlHttp = new window.ActiveXObject('Microsoft.XMLHTTP');
} else {
xmlHttp = new XMLHttpRequest();
}
/*GET方法
// 指定请求方式
xmlHttp.open('GET','http://localhost/ajax/ajax.php?username=jimmy&age=28',true);
//发送请求
xmlHttp.send();*/
//POST方法
xmlHttp.open('POST','http://localhost/ajax/ajax.php',true);
xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
//发送请求
xmlHttp.send('username=jiming&age=28');
//等待接收结果
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status === 200) {
// console.log(xmlHttp.responseText);
// console.log(xmlHttp.statusText);
/* aCity = xmlHttp.responseXML.getElementsByTagName()
console.log(xmlHttp.responseXML);//返回xml对象*/
}
}
}
}
}
</script>
</head>
<body>
<button id="send">发送</button>
</body>
</html>
后端PHP代码:
<?php
header("Access-Control-Allow-Origin:*");
//$username = $_GET['username'];
//$age = $_GET['age'];
$username = $_POST['username'];
$age = $_POST['age'];
echo '我叫'.$username.'今年:'.$age;
?>