对于 html中的from表单标签的使用和Ajax对象创建
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- <form action="http://111.229.6.231:9996/v1/get" method="get">
<input type="text" name="name" placeholder="请输入用户名">
<br>
<input type="text" name="pwd" placeholder="请输入密码">
<br>
<input type="submit" value="提交-get">
</form>
<form action="http://111.229.6.231:9996/v1/POST" method="POST">
<input type="text" name="name" placeholder="请输入用户名">
<br>
<input type="text" name="pwd" placeholder="请输入密码">
<br>
<input type="submit" value="提交-POST">
</form>
<video src=""></video> -->
<button>提交</button>
<!-- <script>
let btn = document.querySelector('button')
btn.onclick =function(){
//创建一个ajax对象xhr
let xhr =new XMLHttpRequest()
//请求 行 头 体
//open('get','ul地址')
// xhr.open('get','http://111.229.6.231:9996/v1/get')
//头默认添加 不需要加
//体
// xhr.send()
//get可以添加在UL后面
xhr.open('get','http://111.229.6.231:9996/v1/get?name=andmin&pwd=123456789')
}
</script> -->
<!-- ajax POST版本 -->
<script>
// let btn = document.querySelector('button')
// btn.onclick = function () {
// //创建
// let xhr = new XMLHttpRequest()
// //请求
// //行
// xhr.open('post', 'http://111.229.6.231:9996/v1/post')
// //头
// xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
// //体
// xhr.send('name=admin&pwd=123456')
// }
//响应
let btn = document.querySelector('button')
btn.onclick =function(){
//创建一个ajax对象xhr
let xhr =new XMLHttpRequest()
//请求 行 头 体
//open('get','ul地址')
// xhr.open('get','http://111.229.6.231:9996/v1/get')
//头默认添加 不需要加
//体521``
// xhr.send()
//get可以添加在UL后面
xhr.open('get','http://111.229.6.231:9996/v1/get?name=andmin&pwd=123456789')
//响应
xhr.onload =function(){
console.log(xhr);
}
}
</script>
</body>
</html>
新增语句:
action:
指定表单的提交地址
let xhr=nwe XMLHttpRequest
新创建的Ajax对象 其中xhr属于变量
xhr.open('get','url地址')
请求 行 get/post 属于 表单的提交方式 默认情况下为get
get的表单数据可以直接在url的地址中看到 而 post却不会 所以 post相对安全些 get的输入有长度限制 最大不超过4KB 但是post却没有)
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
请求头
get的头属于默认添加 所以可以不加 但是post需要添加
xhr.send('name=admin&pwd=123456')
请求 体
get的可以添加在 URL地址后面 但是post需要添加
xhr.onload =function(){
console.log(xhr);
}
}
响应
服务器以HTTP协议要求的格式把内容返回到客户端的这种行为叫做响应
let btn = document.querySelector('button')
btn.onclick=function(){
let txt=document.querySelector('.txt').value
let pwd=document.querySelector('.pwd').value
let xhr = new XMLHttpRequest()
xhr.open('post','http://111.229.6.231:9996/v1/post')
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.send(`name=${txt}&pwd=${pwd}`)
xhr.onload= function () {
if (xhr.responseText === '登录成功') {
alert('登录成功')
location.href='http://www.bilibili.com'
}else{
alert('登录失败')
}
}
}
</scrip
注意点:
if (xhr.responseText === '登录成功')
等于的值一定要与 返回的内容相同