我在 Web Node/Express Web 应用程序上有一个基本的消息服务,并且我正在尝试使用 FormData 对象通过 Ajax 提交表单。
如果我在没有 AJAX 的情况下提交表单,则一切正常,但使用 AJAX 则 req.body。都是未定义的。
在服务器上,使用 AJAX 时我需要在 req.body 以外的地方查找数据??
创建 FormData 对象:
var ajaxData = new FormData;
ajaxData.append('newMessage', $('.new-message').val()) // I've console.logged these, and their values are correct
ajaxData.append('senderId', $('[name="senderId"]').val())
ajaxData.append('senderName', $('[name="senderName"]').val())// I've console.logged these, and their values are correct
ajaxData.append('recipientId', $('[name="recipientId"]').val())
ajaxData.append('recipientName', $('[name="recipientName"]').val())// I've console.logged these, and their values are correct
这是 POST 请求:
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
dataType: false,
cache: false,
contentType: false,
processData: false,
complete: function() {
console.log('message created');
},
success: function(data) {
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(errorThrown);
}
});
编辑
感谢 G. Mansour 在下面的回答。万一其他人到达这里,问题就出在这行:
contentType: false,
我在某个时候尝试过这条线,但也不起作用
contentType: 'application/json',
但是当我完全删除这条线时,一切都正常工作...如果有人能告诉我为什么这条线会破坏一切,我很想知道。
最佳答案
这是html部分
<form id="form" action="" method="post">
<input type="text" name="msgID" id="msgID">
<input type="text" name="senderId" id="senderId">
<input type="text" name="senderName" id="senderName">
<input type="text" name="recipientId" id="recipientId">
<input type="text" name="recipientName" id="recipientName">
<input type="submit" name="dsq" value="dsqdsq">
</form>
这是 JavaScript 部分
<script type="text/javascript">
$(document).ready(function(){
$("#form").submit(function(){
$.ajax({
url: "test.php",
data: $("#form").serialize(),
type: "POST",
dataType: 'json',
success: function (e) {
console.log(JSON.stringify(e));
},
error:function(e){
console.log(JSON.stringify(e));
}
});
return false;
});
});
</script>
这是 php 代码
<?php
die(json_encode(array("status"=>true)));
?>
希望对您有帮助。
关于javascript - 通过 JQuery Ajax Post 请求提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39948002/