我正在向服务器发送 Ajax post 请求,所有数据都正常,但我的名字和姓氏正在更新为“未定义” 请帮忙提前致谢
--- 服务器代码 ---
我在查询中插入这个变量,这样数据库就可以用那个值更新
app.post("/postData", function (req, res) {
var first_name = req.body.fname
var last_name = req.body.lname
var email = req.body.email
var comment = req.body.comment
var insert_query = "INSERT into form_data(sno,fname,lname,email,comments) values(" + "1" + "," + "'" + first_name + "'" + "," + "'" + last_name + "'" + "," + "'" + email + "'" + "," + "'" + comment + "'" + ")";
connector.query(insert_query, function (err, res) {
if (err) {
var insert_query1 = "INSERT into form_data(sno,fname,lname,email,comments) values(" + "''" + "," + "'" + first_name + "'" + "," + "'" + last_name + "'" + "," + "'" + email + "'" + "," + "'" + comment + "'" + ")";
connector.query(insert_query1,function(err,res){
if (err) {
console.log("Query Error")
} else {
console.log("Failed data updated")
console.log(insert_query1)
}
})
} else {
console.log("Data Updated")
}
})
})
app.listen(1337, function (err) {
if (err) {
console.log(err)
} else {
console.log("Connection Established at port:1337")
}
})
--- HTML ---
这是单击必须执行 ajax 请求的按钮时的表单
<script>
$(document).ready(function () {
$("#btn").click(function(event){
event.preventDefault();
$.ajax({
url : "http://127.0.0.1:1337/postData",
type : "POST",
data : {
"first_name" : $("#fn").val(),
"last_name" : $("#ln").val(),
"email" : $("#em").val(),
"comment" : $("#com").val()
},
dataType : "json",
success : function(){
console.log(data)
}
})
})
})
</script>
<form id="frm1">
<label for="name1">First name</label>
<input type="text" name="fname" id="fn" value=""><br><br>
<label for="name2">Last name</label>
<input type="text" name="lname" id="ln" value=""><br><br>
<label for="femail">Email</label>
<input type="email" name="email" id="em" value=""><br><br>
<label for="comm">Comments</label>
<textarea cols="20" rows="10" id="com" name="comment"></textarea><br><br>
<input type="submit" value="Submit" id="btn">
<input type="reset" value="Reset" id="rest">
<input type="button" value="Delete" id="del">
</form>
'
--- 错误---
这是我遇到的错误
最佳答案
<script>
$(document).ready(function () {
$("#btn").click(function(event){
event.preventDefault();
$.ajax({
url : "http://127.0.0.1:1337/postData",
type : "POST",
data : {
"fname" : $("#fn").val(),
"lname" : $("#ln").val(),
"email" : $("#em").val(),
"comment" : $("#com").val()
},
dataType : "json",
success : function(){
console.log(data)
}
})
})
})
</script>
关于jquery - 我正在向服务器发出 Ajax 发布请求,所有数据都很好,但我的名字和姓氏正在更新为 "undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59007267/