我有一个触发ajax请求的html页面:
$.ajax({
type: 'POST',
url: '/usernamecheck',
data: {"username":username},
success: function(taken){
if(taken === 0){
$('#error').text('The username' + username + ' is available!')
}else{
$('#error').text('The username' + username + ' is not available')
}
},
dataType: "json"
})
这是我的node.js代码:
exports.usernameCheck = function(req,res){
var db;
db = require('./../custom_modules/db.js');
var username = req.body.username;
db.users.find({username:username},function(err,users){
console.log(username)
if(users.length === 0){
//return 0
}else{
//return1
}
})
我想用node.js请求回复这个ajax,但我不知道该怎么做?
答案 0 :(得分:3)
jQuery ajax dataType
表示您期望从服务器返回的数据。我将此保留为json,只需更改代码的其他部分以适应数据类型。
<强>客户端强>
$.ajax({
type: 'POST',
url: '/usernamecheck',
data: {"username":username},
success: function(response){
if( response.taken === true){
$('#error').text('The username' + username + ' is available!')
}else{
$('#error').text('The username' + username + ' is not available')
}
},
dataType: "json"
})
<强>节点强>
db.users.find({username:username},function(err,users){
res.json({taken: users.length !== 0})
})