jQuery 序列化数据和 PHP $_POST 不匹配

Posted

技术标签:

【中文标题】jQuery 序列化数据和 PHP $_POST 不匹配【英文标题】:jQuery serialized data and PHP $_POST don't match 【发布时间】:2016-05-08 10:22:38 【问题描述】:

我有一个带有表单的页面。 此表单具有不同的“表格”,当用户浏览这些表格时,使用$.ajax 从网站调用信息,并且该表格获得动态添加的输入。

最后,我试图将此表单数据发布到 php 文件中。

我不会转储我的整个代码,因为它有很多规则。但这是我用来发帖的部分:

function postForm() 
    ...
    var data = $('form.feedForm').serialize();
    //console.log( data );      
    $.post('.../get.php?feed_add_save_feeding', data )
    .fail( function() 
        console.log('fail');
        ...
    )
    .success( function(data) 
        console.log('success');
        console.log(data);
        ...
    )

在我的 PHP 中,我添加了这个,看看会发生什么:

print_r( $_POST );

查看我的控制台,我看到这些参数已发布:

dateType              now
date_d                30
date_m                1
date_y                2016
time_h                19
time_m                27
time_s                42
herd_num_animals      150
herd                  85
menu                  26
feedtype_total_value  3639
tWeight               3639
weightCumu            3637
supps_name[29]        Test voer 1
supps_price[29]       128
supps_dry_weight[29]  94
supps_weight[29]      1837
supps_name[34]        Test voer 6
supps_price[34]       18
supps_dry_weight[34]  70
supps_weight[34]      1800
supps_name[30]        Test voer 2
supps_price[30]       160
supps_dry_weight[30]  50
supps_weight[30]      1
user_id               1

PHP 中的输出是

Array
(
    [dateType] => now
    [date_d] => 30
    [date_m] => 1
    [date_y] => 2016
    [time_h] => 19
    [time_m] => 27
    [time_s] => 42
    [herd_num_animals] => 150
    [herd] => 85
    [menu] => 26
    [feedtype_total_value] => 3639
    [tWeight] => 3639
    [weightCumu] => 3637
    [supps_name] => Test voer 6
    [supps_price] => 18
    [supps_dry_weight] => 70
    [supps_weight] => 1837
)

为什么不是所有提交的输入都通过 PHP??

(注意:由于篇幅原因,我故意省略了我的代码。如果我应该添加一些或全部,请发表评论)

编辑

这是完整的 JS 代码和渲染的 html(从 Firebug 复制):

JSFiddle (just the code, not a working demo)

【问题讨论】:

当你说console时,你指的是网络标签吗? @JosephtheDreamer firebug 中的控制台 supps_name[29] 这样发送的变量将是php $_POST == $_POST['supps_name'][29] 中的数组 @LinkinTED 这有点令人困惑......如果它们重复,你需要在 html 名称中使用 []...... html 未显示 @DelightedD0D,它适用于 get.php 中的所有其他情况。但是,将 POST 更改为 GET,似乎确实可以解决问题。感谢大家的帮助 【参考方案1】:

我看到的是您发送了几个数组,并且正确的数组键显示在输出中

supps_name[29]这样的post body中发送的变量将是php中的数组

is_array($_POST['supps_name'])// true

您的 html 输入应如下所示

<input name="supps_name[]">

OR 与定义的键

<input name="supps_name[1]">

【讨论】:

我使用了var_dump($_POST['supps_name'],它给了我string(11) "Test voer 6"...它确实应该是一个数组。

以上是关于jQuery 序列化数据和 PHP $_POST 不匹配的主要内容,如果未能解决你的问题,请参考以下文章

使用 jQuery 和 PHP 序列化和提交表单

PHP 不捕获由 ajax jquery 在同一页面上发送的 $_POST 数据

通过JQuery的$.ajax()把 json 数据 post 给 PHP

PHP如何处理jquery post过来的$serialize数据

$.post 不向 php 脚本发送数据

将 PHP $_POST 数组传递给 javascript/jQuery 以通过 ajax 发送回 PHP