我使用serializeArray()获取表单输入元素值,但是当我这样做时,有一个额外的数组换行,如何避免这个
<form method="post" class="form" action="<?=site_url('update_description');?>" role="form" data-toggle="validator">
<input type="hidden" name="id" value="<?=$info['id'];?>">
<textarea placeholder="Enter Property Description" class="form-control" name="description" rows="4" required><?= $info['description'];?></textarea>
<button type="submit" class="btn btn-sm">Update Description</button>
<script>
</form>
$('.form').submit(function(e) {
e.preventDefault();
var params = $(this).serializeArray();
$.post($(this).attr('action'),
{params},
function(data){
//console.log(data);
});
});
</script>
我在控制器中获取这样的数据
Array
(
[params] => Array
(
[0] => Array
(
[name] => id
[value] => 44
)
[1] => Array
(
[name] => description
[value] => hello
)
)
)
答案 0 :(得分:1)
您可以使用reduce()将输出转换为形状为对名称/值对象的post参数:
var params = $(this).serializeArray().reduce(function(acc, ele) {
acc[ele.name] = ele.value;
return acc;
}, {});
此外,您需要更改:
{params},
为:
params,
$('.form').submit(function(e) {
e.preventDefault();
var params = $(this).serializeArray().reduce(function(acc, ele) {
acc[ele.name] = ele.value;
return acc;
}, {});
console.log(params);
return;
// useless for test
$.post($(this).attr('action'),
params,
function(data){
//console.log(data);
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" class="form" action="<?=site_url('update_description');?>" role="form" data-toggle="validator">
<input type="hidden" name="id" value="<?=$info['id'];?>">
<textarea placeholder="Enter Property Description" class="form-control" name="description" rows="4" required><?= $info['description'];?></textarea>
<button type="submit" class="btn btn-sm">Update Description</button>
</form>
&#13;
答案 1 :(得分:0)