关于ajax请求,表单请求,以及nodejs响应

前端jQuery ajax片段
<!DOCTYPE html>
<html>
<head></head>
<body>
<div>
    <label>
        姓名:
        <input type="" name="name"></label>
    <label>
        密码:
        <input type="" name="password"></label>
    <button onclick="toSubmit()" type="">提交</button>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script type="text/javascript">
    function toSubmit() {
    const data = {
        name: $('[name="name"]').val(),
        password: $('[name="password"]').val(),
    }
    // 返回对象可通过xhr.responseJSON获得
    // 返回字符串可通过xhr.responseText获得
    // success 也可通过data获得 
    // textStatus 返回状态码
    // 使用GET方法就type: 'GET',
    $.ajax({
        url: '/ajax',
        type: 'POST',
        data: data,
        success: function (data, textStatus, xhr) {
            console.log(data);
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log(xhr);
        }
    });
}
</script>
</html>
nodejs使用express片段
router.post('/ajax', function(req, res, next) {
    const data={
        name:req.body.name,
        password:req.body.password
    }
    // 如果使用GET请求
    // const data={
    //  name:req.query.name,
    //  password:req.query.password
    // }
    console.log(data);
    for (let obj in data){
        if (undefined ==data[obj]||'' ==data[obj]){
            //res.send(500,'错误');
            res.send(500,{code:'-1',mes:`参数${obj}错误`});
            return;
        }
    }
    //res.send(200,'成功');
    res.send(200,{code:'0',mes:'成功'});
});

如果使用ajax请求只是为了使页面跳转如并且不校验

success: function(data, textStatus, xhr) {
    window.location.href='';
},

最好改用表单提交

<form method="POST" action="/ajax">
    <label>
        姓名:
        <input type="" name="name"></label>
    <label>
        密码:
        <input type="" name="password"></label>
    <button type="submit">提交</button>
</form>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值