node.js ajax post方式 判断用户名是否可用
http.js
var http = require('http'); var url = require('url'); var fs = require('fs'); var server = http.createServer(); server.listen(8000,function(){ console.log('启动成功'); }) server.on('request',function(req,res){ var urls = url.parse(req.url,true); if(urls.pathname == '/test'){ res.setHeader('content-type','text/html;charset=utf-8'); var d = ''; //接收数据 req.on('data',function(post_data){ d+=post_data; }) //接收结束 req.on('end',function(){ var obj = require('querystring').parse(d);//解析数据 //console.log(obj); if(obj.name == 'admin'){ res.end('1'); }else{ res.end('0'); } }) }else{ fs.readFile('.'+urls.pathname,'utf8',function(err,data){ if(!err){ res.end(data); }else{ res.end(''); } }) } })
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Demo</title> </head> <body> <input type="text" name="name" id="txt"> <span id="s"></span> </body> <script> var txt = document.getElementById('txt'); txt.onblur = function(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.responseText == 1){ //不可用 var h = '<font color="red">不可用</font>'; document.getElementById('s').innerHTML=h; }else{ //可用 var h = '<font color="green">可用</font>'; document.getElementById('s').innerHTML=h; } } } xhr.open('post','http://127.0.0.1:8000/test'); xhr.send('name='+txt.value); } </script> </html>

浙公网安备 33010602011771号