- 創(chuàng)建form表單也榄,給用戶輸入信息
- 獲取提交按鈕呢燥,并添加點擊的時間
- 給予提交按鈕一個回調函數夹厌,并用return false語句禁止提交按鈕的默認行為
創(chuàng)建一個Ajax對象
創(chuàng)建請求監(jiān)聽并判斷 - 獲取用戶的參數來構建一個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('監(jiān)聽到狀態(tài)變化'+xhr.readyState+'<br>');
if (xhr.readyState == 4 && xhr.status == 200){
console.log('發(fā)送成功 接收成功<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發(fā)送數據
xhr.send(null);
return false;
}
</script>
</html>
test.php代碼如下
<?php
echo "ggg";
?>