ajax02
目录
前言
ajax02学习开始
一、复习
二、跨域错误提示
三、Ajax发送POST请求
- 相比GET请求,POST请求需要在请求头中设置编码的类型
- POST传参的方式是放入到请求体中
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') 设置传参类型 a=1&b=2 xhr.send('a=1&b=2') 参数通过请求体传递
- 案例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>用户登录</title> </head> <body> 用户<input type="text" id="user"><br> 密码<input type="text" id="pwd"><br> <button id="btn">登录</button> <script> // 给按钮绑定点击事件 btn.onclick = function(){ var a = user.value var b = pwd.value console.log(a,b) // 发送AJAX步骤 // 1.创建HTTP请求对象 var xhr = new XMLHttpRequest() // 2.打开服务器的连接,请求接口 // GET传参拼接到URL xhr.open('GET',`http://127.0.0.1:3000/login?user=${a}&pwd=${b}`,true) // 3.发送请求 xhr.send() // 4.添加事件,监听响应,获取响应结果 xhr.onload = function(){ alert( xhr.responseText ) } } </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>用户注册</title> </head> <body> 用户<input type="text" id="user"><br> 密码<input type="text" id="pwd"><br> 邮箱<input type="text" id="email"><br> 手机<input type="text" id="phone"><br> <button id="btn">注册</button> <script> // 按钮绑定点击事件,获取输入的值 btn.onclick = function(){ var a = user.value var b = pwd.value var c = email.value var d = phone.value console.log(a,b,c,d) // 创建HTTP请求对象 var xhr = new XMLHttpRequest() // 打开服务器的连接,请求接口 xhr.open('POST','http://127.0.0.1:3000/reg',true) // POST传参还需要设置编码类型 a=1&b=2 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8') // 发送请求,post传参将参数放入到请求体 xhr.send(`user=${a}&pwd=${b}&email=${c}&phone=${d}`) // 添加事件,监听服务器端响应,获取响应结果 xhr.onload = function(){ console.log( xhr.responseText ) } } </script> </body> </html>
练习:新建04_add.html,点击提交 传递姓名,性别,生日,工资,部门编号,
请求添加员工的接口(post http://127.0.0.1:3000/add)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>添加员工</title> </head> <body> 姓名<input type="text" id="ename"><br> 性别<select id="sex"> <option value="1">男</option> <option value="0">女</option> </select> <br> 生日<input type="text" id="birthday"><br> 工资<input type="text" id="salary"><br> 部门<select id="deptid"> <option value="10">研发部</option> <option value="20">运营部</option> <option value="30">市场部</option> <option value="40">测试部</option> </select> <br> <button id="btn">提交</button> <script> // 给按钮绑定点击事件 btn.onclick = function(){ // 获取用户输入的值 var a = ename.value var b = sex.value var c = birthday.value var d = salary.value var e = deptid.value console.log(a,b,c,d,e) // 1.创建HTTP请求对象 var xhr = new XMLHttpRequest() // 2.打开服务器的连接,请求接口 xhr.open('POST','http://127.0.0.1:3000/add',true) // 3.设置请求头中,post传参的编码类型 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8') // 4.发送请求,传递post的参数 xhr.send(`ename=${a}&sex=${b}&birthday=${c}&salary=${d}&deptid=${e}`) // 5.添加事件,监听响应,获取响应结果 xhr.onload = function(){ console.log(xhr.responseText) } } </script> </body> </html>
四、JSON
叫做JS对象表示法,使用JS对象形式来描述一组数据,是前后端数据交换的一种形式
属性名必须使用双引号,属性值是字符串的话必须用双引号
总结
Ajax02学习结束