ajax node.js

ajax通过一个编号请求对应的姓名。

node.js服务:

/**
 * Created by tujiaw on 15/8/14.
 */
var express = require('express');
var app = express();

app.use(express.static(__dirname));

var users = [
    {
        number:123456,
        name:"tujiaw"
    },
    {
        number:654321,
        name:"hello"
    },
];

app.get('/query', function(req, res) {
    var number = req.query.number;
    if (number) {
        var isFind = false;
        for (i in users) {
            if (users[i].number == number) {
                res.json(users[i]);
                isFind = true;
                break;
            }
        }
        if (!isFind) {
            res.json({errCode:1, errString:"not find"});
        }
    }
});

app.listen(3200);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
    <title>Ajax Demo</title>
    <style>
        body, input, button {
            font-size:30px;
            line-height:1.5;
        }

    </style>
</head>
<body>
<label>请输入编号</label>
<input type="text" id="keyword"/>
<button id="search">查询</button>
<p id="searchResult"></p>

<script>
    // ------ XMLHttpRequest ------
//    document.getElementById("search").onclick = function() {
//        var request = new XMLHttpRequest();
//        request.open("GET", "query?number=" + document.getElementById("keyword").value);
//        request.send();
//        request.onreadystatechange = function() {
//            var searchResult = document.getElementById("searchResult");
//            if (request.readyState === 4) {
//                if (request.status === 200) {
//                    searchResult.innerHTML = request.responseText;
//                } else {
//                    searchResult.innerHTML = "status:" + request.status;
//                }
//            } else {
//                searchResult.innerHTML = "read state:" + request.readyState;
//            }
//        }
//    };

    // ------ ajax jquery------
    $('#search').click(function(e) {
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: 'query?number=' + $('#keyword').val()
        }).done(function(result) {
            if (result.number) {
                $('#searchResult').html('number:' + result.number + ", name:" + result.name);
            } else if (result.errCode) {
                $('#searchResult').html('errCode:' + result.errCode + ", errString:" + result.errString);
            } else {
                $('#searchResult').html('error');
            }
        })
    });
</script>
</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值