您的位置:首页 > 编程语言

AJAX中POST请求和服务器完整代码

2017-07-30 11:46 211 查看
前端代码:

<html>  

<head>  

<meta charset="utf-8">  

<title>登录</title>  

<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>  

<script>  

$(function(){    

    $('#btn').click(function(e){  

        e.preventDefault();   

        $.ajax({  

             cache: true,  

                type: "POST",                       //采用POST请求  

                url:"http://110.64.72.18:8888/test",//服务器URL  

                data:$('#user_form').serialize(),                 

                async: true,  

                error: function(res) {      //连接失败的情况  

                      //console.log(res)             

                alert("Connection error");  

                },  

                success: function(res) {    //连接成功的情况服务器返回res  

                        console.log(res)   

                           if(res === "success"){  

                            alert("登录成功"); }      //对服务器返回值res判断,如果res是success则弹出登录成功  

               else{  

               alert("登录失败");         //判断错误打印失败  

                        }  

                }  

                });  

                   });  

        });  

</script>  

<link rel="stylesheet" type="text/css" href="style.css" charset="utf-8"></link>  

</head>  

<body style="background-image:url(/images/薰_01.png);background-position:center;background-repeat:no-repeat">      

<div style="background:#FFFAFA;background-color:rgba(255,255,255,0.6);border:1px solid #000;position:absolute;width:400px;height:300px;top:50%;left:50%;margin-left:-200px;margin-top:-150px;text-align:center">  

<h1 style="padding-top:10px;text-shadow:5px 5px 5px darkgrey">登录界面</h1> <!--登录标题-->  

  

<form autocomplete="on" id="user_form"><!--form表单提交 id用于post对表单的获取-->  

<div>  

<p style="padding-top:10px">登录: <input type="text" name="xxx" id="xxx" /></p>  

<p style="padding-top:10px">密码: <input type="text" name="pw" id="pw" </p><!--id用于前端自己的标识,name用于服务器对前端信息的标识-->  

</div>  

</form>  

<p style="padding-top:10px;font-size:10px;font-weight:bold;text-shadow:5px 5px 5px grey"> * 登录账号为工号;默认登录密码为123456!</p>  

<input style="background:royalblue;width:100px;height:40px;margin-top:10px;  

text-decoration:none;color:white;font-size:20px;font-weight:bold"  

 id="btn" type="submit" value="登录"/>  

</div>  

</body>  

</html>  

服务器代码:

app.post('/test', function (req, res) {  

  

    // res.body.  

    console.log('post')  

    console.log(req.body)  

    console.log(req.body.xxx)  

    if(req.body.xxx === '123456')  

    {     

        res.send('success')   

    }  

    else  

    {  

        res.send('error')  

    }  

})  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐