zoukankan      html  css  js  c++  java
  • 如何在表单中使用Ajax

    1、HTML就是一个简单表单验证,有登录按钮,点击登录会发送Ajax,

    这里就是简单如果用户名为:zhouzhiruo,密码为:123456,就是登录成功,否则登录失败

    应该在发送请求之前对input的value做验证是否符合标准

    <form id="myform" name="myform" action="03.php" method="post">
            <table>
                <tr>
                    <td>用户名:</td>
                    <td><input type="text" id="user" name="user"></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><input type="password" id="pwd" name="pwd"></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="button" id="btn" value="登录"></td>
                </tr>
            </table>
        </form>

    2、JS

    //使用Ajax时候不要用subbmit
        var btn=document.getElementById("btn");
        btn.onclick=function(){
            var xhr=getXhr();
            xhr.open('post','03.php');
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            var user=document.getElementById("user").value;
            var pwd=document.getElementById("pwd").value;
            xhr.send("user="+user+"&pwd="+pwd);
            xhr.onreadystatechange=function(){
            //获得服务器端当前状态
            //alert(xhr.readyState);
            //保证响应完成
                if(xhr.readyState==4){
                    //保证这次请求必须成功
                    //alert(xhr.status);
                    if(xhr.status==200){
                        //接收服务器端的数据
                        var data=xhr.responseText;
                        //测试
                        console.log(data);
                        }
                    }
            }
        };
        function getXhr(){
            var xhr=null;
            if(window.XMLHttpRequest){
                xhr=new XMLHttpRequest();
            }else{
                xhr=new ActiveXObject("Microsoft.XMLHttp");
            }
            return xhr;
        }

    3、PHP,链接数据库的语言之一

    <?php
        $user=$_POST['user'];
        $pwd=$_POST['pwd'];
        if($user=="zhouzhiruo"&$pwd==
            "123456"){
            echo "login successful";
        }else{
            echo "login error";
        }
    ?>
  • 相关阅读:
    完美串(区间dp)
    Brackets(区间dp)
    Eureka的高可用
    在Spring Boot中使用 @ConfigurationProperties 注解
    Spring Boot干货系列:(四)开发Web应用之Thymeleaf篇
    luogu3707 相关分析 (线段树)
    luogu3380/bzoj3196 二逼平衡树 (树状数组套权值线段树)
    bzoj4504 K个串 (优先队列+主席树)
    bzoj4336 骑士的旅行 (树链剖分+multiset)
    suoi37 清点更多船只 (卡空间线段树)
  • 原文地址:https://www.cnblogs.com/-walker/p/6416786.html
Copyright © 2011-2022 走看看