手记

node.js学习--异步通信

待完善

html代码

<form method="post" id="form">
    <label for="username"></label><input type="text" name="username" id="username"><br>
    <label for="password"></label> <input type="password" name="password" id="password"><br>
    <input type="submit" value="表单提交">
</form>
<button id="ajax提交">ajax</button><br>
<label>结果:</label><span id="info"></span>

Node代码

var express = require('express');
var router = express.Router();
router.route('/register').post(function (req, res, next) {
        res.set('Content-Type', 'text/html');
        var username = req.body.username,
            password = req.body.password;
        res.end('成功收到POST请求:'+'username:'+username+",password:"+password);
    });

JavaScs代码

js+ XHR:

var ajax = document.getElementById("ajax"),
        info = document.getElementById("info"),
            form = document.getElementById("form"),
        username = document.getElementById("username"),
        password = document.getElementById("password");
    ajax.onclick = function(){
        var xhr = new XMLHttpRequest();
        xhr.open('post','');//url为空表示在当前页提交
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send("username="+username.value+"&password="+password.value);
        xhr.onreadystatechange=function () {
            if (xhr.readyState == 4&&xhr.status==200){
                info.innerText = xhr.responseText;
            }
        };
    }

JQuery:

$("#ajax").on('click',function () {
        $("#msg").html($("#form").serialize());
        $.post("",$("#form").serialize(),
                function(data){
                    $("#info").html(data);
                });
    })
0人推荐
随时随地看视频
慕课网APP

热门评论

同学这资料是分享还是备忘?

查看全部评论