- 创建form表单,给用户输入信息
- 获取提交按钮,并添加点击的时间
- 给予提交按钮一个回调函数,并用return false语句禁止提交按钮的默认行为
创建一个Ajax对象
创建请求监听并判断 - 获取用户的参数来构建一个uri地址
- 请求方式用get
ajax.html代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="test1.php" method="get">
<input type="text" name="username" id = 'username'>
<input type="password" name="password" id = 'password'>
<input type="submit" name="" id = 'submit'>
</form>
</body>
<script>
var btn = document.getElementById('submit');
btn.onclick = function(){
console.log('点击事件成功<br>');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
console.log('监听到状态变化'+xhr.readyState+'<br>');
if (xhr.readyState == 4 && xhr.status == 200){
console.log('发送成功 接收成功<br>');
document.write(xhr.responseText);
}
}
var username = document.getElementById('username').value; // 获取input里得值
//console.log(username);
var password = document.getElementById('password').value;
var uri = 'test1.php?username='+username+'&password'+password; // 拼接uri请求得地址
document.write(uri);
xhr.open('get',uri,true); // 通过test.php?user=?? & pass=xxx发送数据
xhr.send(null);
return false;
}
</script>
</html>
test.php代码如下
<?php
echo "ggg";
?>