test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>get方式</title>
</head>
<body>
<h1>使用get方式发送数据</h1>
<input type="text" name="content" class="con"></input>
<input type="button" value="提交" id="btn"></input>
</body>
</html>
<script type="text/javascript">
// 绑定点击事件
document.querySelector('#btn').onclick= function(){
// 发送ajax请求的5个步骤
//1.创建异步对象
var ajax = new XMLHttpRequest();
//2.设置请求的url等参数
/*参数1:请求的方法
参数2:请求的url ,get提交的数据是直接追加在url后面的
格式为xxx.php?xxx=xxx
这里动态传递参数
getAjax.php?content='+document.querySelector('.con').value
*/
ajax.open('get','server.php?content='+document.querySelector('.con').value);
//3.发送请求
ajax.send();
//4.注册事件
ajax.onreadystatechange = function(){
// 为了保证数据完整的回来,我们一般会判断两个值
if (ajax.readyState ==4 && ajax.status==200) {
// 如果能够进入这个判断,说明请求的页面存在,且返回数据
//5.在注册事件中 获取返回的内容,并修改页面的显示
// 数据是保存在异步对象的属性中
console.log(ajax.responseText);
document.querySelector('h1').innerHTML = ajax.responseText;
};
}
}
</script>