【Web前端问题】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);

}

})

}


参考:

MDN - FormData()

回答:

其实格式不用管, 后台能取到就行

回答:

不确定,但是感觉 dataType 和 contentType 这两个属性很可疑,建议去掉,尤其是 dataType

以上是 【Web前端问题】ajax formdata格式问题 的全部内容, 来源链接: utcz.com/a/140353.html

回到顶部