I have a html page that triggers an ajax request:
$.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"
})
this is my node.js code:
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
}
})
and I want to respond to this ajax with node.js request but am a little unsure of how to do so?
The jQuery ajax dataType
represents the data your're expecting back from the server. I would leave this as json and just change other parts of your code to accommodate the data type.
Client
$.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"
})
Node
db.users.find({username:username},function(err,users){
res.json({taken: users.length !== 0})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.