我正在尝试向服务器发出 ajax 请求。请求发送成功,但请求体中参数不合适。
正文中显示的参数使用浏览器的网络工具:
{"name":"","message":"","time":1464807897670}
名称 <input>
和消息 <textarea>
字段为空,尽管它们不应该为空。
这是我的 HTML 输入字段:
<div id="writePanel">
<p>Your Name</p>
<input id="writeName" type="text">
<p>Message</p>
<textarea id="writeArea"></textarea>
<div id="sendButton">Send</div>
</div>
这是 JS 代码:
$(document).ready(function() {
var data = {
name: document.getElementById("writeName").value,
message: document.getElementById("writeArea").value,
time: new Date().getTime()
};
$("#sendButton").click(function () {
$.ajax({
type: "POST",
url: "message.receive",
contentType: "application/json",
data: JSON.stringify(data),
success: function (response) {
// ...
}
})
})
})
我错过了什么?
最佳答案
看起来您是在开始时设置值,而不是在按下按钮时设置值。尝试在 ajax 调用之前在 click 函数中设置数据对象中的值:
$("#sendButton").click(function () {
var data = {
name: document.getElementById("writeName").value,
message: document.getElementById("writeArea").value,
time: new Date().getTime()
};
$.ajax({
type: "POST",
url: "message.receive",
contentType: "application/json",
data: JSON.stringify(data),
success: function (response) {
// ...
}
})
})
关于javascript - ajax 请求空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37576990/