Javascript 将表单数据序列化为数组表示法

Javascript 将表单数据序列化为数组表示法,javascript,jquery,forms,http,serialization,Javascript,Jquery,Forms,Http,Serialization,我有这张表格 <form action="" method="post"> <input type="hidden" name="one" value="somevalue"> <input type="hidden" name="two" value="anothervalue"> <input type="hidden" name="three" value="someothervalue"> </form> 而不是:

我有这张表格

<form action="" method="post">
  <input type="hidden" name="one" value="somevalue">
  <input type="hidden" name="two" value="anothervalue">
  <input type="hidden" name="three" value="someothervalue">
</form>
而不是:

one: somevalue
two: anothervalue
three: someothervalue
两项建议:

1) 直接设置名称:

<input type="hidden" name="mydata[one]" value="somevalue">

然后,如果希望通过AJAX+jQuery发送数据,一种方法是使用序列化表单数据。

您不能通过
$.AJAX()
发送数组,但可以发送JSON字符串。所以,像这样的方法是可行的:

var frm = $(document.myform);
var data = JSON.stringify(frm.serializeArray());
例如:

$.ajax({
    type: "POST",
     url: targetURL,
    data: JSON.stringify($('#form').serializeArray())
})
.done(function(data){
      console.log(data);
      return true;
})
.complete(function() {})
.error(function(xhr, textStatus, errorThrown) {
     console.log('ajax loading error...');
     return false;
    }
});

在PHP端,使用
json\u decode
将json转换回数组:

// decode JSON string to PHP object, 2nd param sets to associative array
$decoded = json_decode($_REQUEST['data'],true);

output values:
foreach ($decoded as $value) {
   echo $value["name"] . "=" . $value["value"];
}

参考资料:


是的,第二选择是我最后使用的。我不能修改源HTML表单,这就是我需要客户端解决方案的原因。酷,我忘了告诉我需要客户端解决方案。卢先生指出了正确的方向。谢谢你,伙计。
$.ajax({
    type: "POST",
     url: targetURL,
    data: JSON.stringify($('#form').serializeArray())
})
.done(function(data){
      console.log(data);
      return true;
})
.complete(function() {})
.error(function(xhr, textStatus, errorThrown) {
     console.log('ajax loading error...');
     return false;
    }
});
// decode JSON string to PHP object, 2nd param sets to associative array
$decoded = json_decode($_REQUEST['data'],true);

output values:
foreach ($decoded as $value) {
   echo $value["name"] . "=" . $value["value"];
}