jquery+ajax前后端交互验证用户名是否唯一
前端代码(jQuery+AJAX):
$(document).ready(function() {
$('#username').on('blur', function() {
var username = $(this).val();
if (username != '') {
$.ajax({
url: '/check-username', // 后端接口地址
type: 'POST',
data: { username: username },
success: function(response) {
if (response.status === 'success') {
$('#username-message').text(response.message).css('color', 'green');
} else {
$('#username-message').text(response.message).css('color', 'red');
}
},
error: function() {
alert('Error occurred while checking username. Please try again later.');
}
});
}
});
});
后端代码(Node.js示例):
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/check-username', (req, res) => {
const username = req.body.username;
// 假设检查用户名的逻辑
const isUsernameTaken = false; // 假设用户名不重复
if (isUsernameTaken) {
res.json({ status: 'error', message: 'Username is already taken.' });
} else {
res.json({ status: 'success', message: 'Username is available.' });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
确保后端运行在3000端口,前端代码可以
评论已关闭