ajax node.js

前端之家收集整理的这篇文章主要介绍了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>

原文链接:https://www.f2er.com/ajax/163011.html

猜你在找的Ajax相关文章