【发布时间】:2021-12-07 22:47:25
【问题描述】:
我的表单如下所示:
<form id="invite-form" method="post" action="" >
<input type="text" name=friends[0][first_name] />
<input type="text" name=friends[0][last_name] />
<input type="text" name=friends[0][email] />
<input type="text" name=friends[1][first_name] />
<input type="text" name=friends[1][last_name] />
<input type="text" name=friends[1][email] />
<input type="text" name=friends[2][first_name] />
<input type="text" name=friends[2][last_name] />
<input type="text" name=friends[2][email] />
<input type="submit" value="Invite" />
</form>
这是我的 javascript 代码:
var friends = [];
jQuery("#invite-form").serializeArray().map(function(x){friends[x.name] = x.value;});
var formData = {
'friends' : JSON.stringify(friends),
'action' : 'invite-friends'
};
jQuery.ajax({
type : 'POST',
url : '/invitation.php',
data : formData,
dataType : 'json',
encode : true
}).done(function(data){
console.log(data);
if(data.success == true){
...
它无法正常工作,并且朋友列表未正确发布。如何正确地将这种形式转换为 json 数据?我希望能够将此数据用作常规数组,就好像它是 POST 的常规表单一样。
【问题讨论】:
-
friends[x.name] = x.value你不能那样做。friends是一个数组,而不是一个对象。你需要friends = {} -
你为什么要对 JSON 进行字符串化,然后将其放入另一个对象中?这是没有意义的。不要像那样将两种数据格式混为一谈,这可能会导致您感到困惑(并且从表面上看已经这样做了)。如果这是您的意图,您可以将其作为一个 JSON 对象发送。
formData = JSON.stringify({ 'friends' : (friends), action' : 'invite-friends' });。并确保contentType:"application/json; charset=utf-8"选项当然是在 $.ajax 属性中设置的),最后在 PHP 中正确读取它(谷歌“如何接收 json post php”以获取详细信息)
标签: javascript php jquery ajax post