javascript - ajax formdata格式问题
本文介绍了javascript - ajax formdata格式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
如果用form表单直接提交的话后端可以接收到,开发者工具中返回的FormData是:
但是用new FormData提交就不行,返回的FormData是:
怎样才能让ajax提交的FormData格式与直接提交相同?
html代码是:
<form id="comment-form" action="https://api.staticman.net/v2/entry/zaaaac/comments/master" method="POST" novalidate="novalidate">
<input name="options[slug]" type="hidden" value="test">
<input type="text" name="fields[name]" title="昵称" placeholder="昵称*" required />
<input type="text" name="fields[email]" title="邮箱" placeholder="邮箱*" required />
<input type="text" name="fields[url]" title="网站" placeholder="网站" />
<textarea name="fields[content]" rows="2" title="评论内容" placeholder="评论内容"></textarea>
<button type="button" onclick="postComment();return false;" />发布评论</button>
</form>
相关的jquery代码是:
function postComment() {
var formData = new FormData($("#comment-form")[0]);
$.ajax({
method: 'POST',
url: 'https://api.staticman.net/v2/entry/zaaaac/comments/master',
data: formData,
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
cache: false,
processData: false,
success: function(data) {
alert(data);
}
})
}
解决方案
貌似是因为<Form>
没有name
属性?
修改如下:
HTML:
<form id="comment-form" name="comment-form" novalidate="novalidate">
<input name="options[slug]" type="hidden" value="test">
<input type="text" name="fields[name]" title="昵称" placeholder="昵称*" required />
<input type="text" name="fields[email]" title="邮箱" placeholder="邮箱*" required />
<input type="text" name="fields[url]" title="网站" placeholder="网站" />
<textarea name="fields[content]" rows="2" title="评论内容" placeholder="评论内容"></textarea>
<button type="button" onclick="postComment();return false;" />发布评论</button>
</form>
JavaScript:
function postComment() {
var commentForm = document.getElementById('comment-form');
var formData = new FormData(commentForm);
$.ajax({
method: 'POST',
url: 'https://api.staticman.net/v2/entry/zaaaac/comments/master',
data: formData,
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
cache: false,
processData: false,
success: function(data) {
alert(data);
}
})
}
参考:
这篇关于javascript - ajax formdata格式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文