尝试使用ajax发送数据,但是当我按下"发送"我的浏览器控制台出错:
(并且没有数据发送)
所以我尝试了不同的互联网方法,但没有人能帮助我。还有一个问题,ajax只试图发送我的一半数据参数......
至少我有更多的参数,比如:姓名和姓氏。
这是我的表单:
<form action="/user/change" method="post">
Nickname: <input id="profile_nickname" name='nickname' type="text" value="{{myNickname}}">
Name: <input type="text" id="name" name='profile_name' value="{{myName}}">
Surname: <input type="text" id="surname" name="profile_surname" value="{{mySurname}}">
Age: <input id="profile_age" name="age" type="text" value="{{myAge}}">
Country: <input type="text" id="profile_country" name="country" value="{{myCountry}}">,
City: <input type="text" id="profile_city" name="city" value="{{myCity}}"></li>
Phone: <input type="text" id="profile_phone" name="phone" value="{{myPhone}}"></li>
<input type="hidden" name="_csrf" value='{{csrfToken}}'>
<input type="submit" value="Send" id="send_profile" class="profile-data_submit">
</form>
我的AJAX脚本:
$('#send_profile').click(function(e) {
e.preventDefault();
$.ajax({
contentType:"application/x-javascript; charset:UTF-8",
global: false,
type: 'POST',
url: '/user/change',
dataType: 'html',
data: {
name: $("#profile_name").val(),
nickname: $("#profile_nickname").val(),
surname: $("#profile_surname").val(),
country: $("#profile_country").val(),
city: $("#profile_city").val(),
phone: $("#profile_phone").val(),
age: $("#profile_age").val()
},
success: function (result) {
console.log(result);
},
error: function (request, status, error) {
console.log(error);
}
});
});
我的后端代码,应更新数据库中的数据:
router.post('/change', function (req, res) {
var nickname = req.body.nickname,
name = req.body.name,
surname = req.body.surname,
age = req.body.age,
country = req.body.country,
city = req.body.city,
phone = req.body.phone;
User.findOneAndUpdate({_id: req.user._id}, {$set:{ nickname: nickname, name: name, surname: surname, age: age, country: country, city: city, phoneNumber: phone }}, {new: true}, function(err, doc){
if(err){
console.log("Something wrong when updating data!");
}
});
});
没有AJAX,它很不错,但是我需要刷新数据而不需要重新加载页面......