我正在向服务器发出 Ajax 发布请求,所有数据都很好,但我的名字和姓氏正在更新为“未定义”
Posted
技术标签:
【中文标题】我正在向服务器发出 Ajax 发布请求,所有数据都很好,但我的名字和姓氏正在更新为“未定义”【英文标题】:I am doing a Ajax post request to the server all the data is fine but my first_name and last_name are being updated as "undefined" 【发布时间】:2020-03-19 07:04:30 【问题描述】:请帮忙提前谢谢
--- 服务器代码 ---
我将在查询中插入此变量,以便可以使用该值更新数据库
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>
'
--- 错误---
这是我遇到的错误
【问题讨论】:
【参考方案1】: <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>
【讨论】:
以上是关于我正在向服务器发出 Ajax 发布请求,所有数据都很好,但我的名字和姓氏正在更新为“未定义”的主要内容,如果未能解决你的问题,请参考以下文章
Django CSRFToken 中间件附加到 URL 并在向服务器发出“PUT”请求后显示。 (AJAX 问题)
向具有不同域和基本身份验证的服务器发出 ajax POST 请求是不可能的吗?