问题
I have a basic messaging service on a web Node / Express web app, and I'm trying to submit the form via Ajax, using the FormData object.
If I submit the form without AJAX, then everything works fine, but with AJAX the req.body. are all undefined.
On the server, I need to look for the data somewhere other than req.body when using AJAX??
Creating the FormData object:
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
And this is the POST request:
$.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);
}
});
EDIT
Thanks to G. Mansour for his answers below. In case anyone else gets here, the issue was the line:
contentType: false,
I tried this line at some point, which also doesn't work
contentType: 'application/json',
But when I remove the line entirely, everything is working as normal... If anyone can tell me why this line was breaking everything, I'd be interested to know.
回答1:
This is the html part
<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>
this is the JavaScript part
<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>
And this is the php code
<?php
die(json_encode(array("status"=>true)));
?>
Hope that will helps you.
回答2:
I checked your code it says that's
Illegal invocation
So i'll give a solution you can use
data: $form.serialize(),
dataType: 'json',
And then you can catch your returned result by
console.log(JSON.stringify(e));
Wish that helps. If you have some errors i can help you.
来源:https://stackoverflow.com/questions/39948002/submitting-form-via-jquery-ajax-post-request