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

来源:互联网 发布:mac sleep命令 编辑:程序博客网 时间:2024/05/22 03:42

前端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>
原创粉丝点击