【个人笔记】《知了堂》ajax的get及post请求

 ajax

执行步骤

// 步骤

设置事件 调用函数

  1. 创建一个XHR对象
  2. 打开ajax通道,链接服务器,配置请求信息和参数
  3. 发送数据
  4. 设置回调函数
  5. 服务器接受请求,处理请求,查询数据库,响应 及 返回数据
  6. 回调函数接受数据,执行回调函数
  7. 回调函数中 更新页面。

  示例:

    

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>表单</title>
</head>
<body>
    <form action="login" method="get">
        <h1>登陆</h1>
        用户名:<input type="text" name="userName" onblur="checkUser()">
        <span id="msg"></span>
        密码:<input type="password" name="pwd">
        <input type="submit">
    </form>
    <script>
        function checkUser(){
            var userName=document.forms[0].elements[0].value;
            var xhr='';
            if(window.XMLHttpRequest){
                xhr=new XMLHttpRequest();//DOM
            }else if(window.ActiveXObject){
                xhr=new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器标准
            }
            // 打开链接配置参数,
            // *   1、 请求方式  就是要告诉它是get、post
            // *   2、 请求地址 url
            // *   3、同步 还是 异步(async),这个跟页面刷不刷新没有关系,是对程序本身的考虑,默认是异步请求true,true异步请求,这个是ajax里面的两个机制,true是异步表示当有东西回来了才执行,同步请求是false是比如有多个ajax请求,他会等一个结束了才执行第二个,
            xhr.open("get","checkUser.do?userName="+userName,true);
            xhr.send(null);//get方式 send是null
       //请求过后会有一个回调函数等待服务器响应在接受数据 xhr.onreadystatechange=function(){ console.log(xhr.responseText) } } </script> </body> </html>

连接数据库
   示例:

const mysql=require("mysql"); //引用数据库模块
const checkUser=function(req,resp){
    console.log(req)
    let userName=req.query.userName;
    let pool=mysql.createPool({
        host:"主机地址",
        port:"主机端口",
        user:"用户名",
        password:"主机密码",
        database:"数据库名"
    })
    pool.getConnection(function(error,connection){
        if(error){
            console.log(error)
        }
        let sqlStr="select * from t_user where u_name=?";
        connection.query(sqlStr,[userName],function(err,data){
            console.log(data)
       //因为是注册嘛所以是data的长度大于0的时候说明数据库里面已经有这个账号了
       if(data.length>0){ resp.send("用户名已经存在"); }else{ resp.send("你好棒,快去注册吧。"); } }); connection.release(); }) } module.exports={ checkUser:checkUser
}

服务器引用

const loginCheck=require("数据库模板地址");

服务器拦截请求

app.get("/拦截地址",loginCheck.checkUser)

 

原文地址:https://www.cnblogs.com/1542986913Yu/p/7603304.html