【问题标题】:Accessing hidden input array using ajax / php使用 ajax / php 访问隐藏的输入数组
【发布时间】:2015-11-15 22:40:40
【问题描述】:

我的表单包含以下几种类型的元素

<input type="hidden" name="selected_models[]" value="1">1</td>
<input type="hidden" name="selected_models[]" value="2">2</td>
<input type="hidden" name="selected_models[]" value="3">3</td>
<input type="hidden" name="selected_models[]" value="4">4</td>

我正在尝试将此数组以及所有其他表单数据传递给 jQuery $.post 函数,但我无法正确访问 php 中的数据。

我尝试使用以下 (jQuery) 传递它:

var _data = { models: $('input[name="selected_models[]"]').serialize() }

然后在 PHP 中使用:

$models = $_POST['models'];

只是为了尝试检查数据,我将此变量传递给 ajax 响应,并使用以下命令将其记录回控制台:

Php
$response = jseon_encode( 
    array(
        'success' => true,
        'models' => json_encode($models)
    ) 
);

JS
console.log(JSON.parse(response.models)

输出如下:

selected_models%5B%5D=37&selected_models%5B%5D=51&selected_models%5B%5D=57

所以,老实说,现在我只是纠结于如何在 php 中循环遍历这些值,因此我实际上可以对它们做一些事情。理想情况下,我可以这样做:

Php
foreach ( $models as $model ) {
    $id = $model.selected_models
    // Do more stuff
}

但这不起作用。我做错了什么?

【问题讨论】:

  • 我能看到html表单吗?

标签: javascript php jquery arrays ajax


【解决方案1】:

我最终在 jQuery 中解决了这个问题,并将解析后的值传递给 PHP,而不是:

var uniqueModels = [];

if ( document.getElementById('acInheritFromVehicle').checked ) {
    var models = jQuery( 'input[name="selected_models[]"]:checked');
    var modelIDs = [];

    //console.log(models);

    models.each(function() {
        if( jQuery.inArray( ))
        modelIDs.push( jQuery(this).val() );
    });

    uniqueModels = unique(modelIDs);

    uniqueModels = jQuery.grep( uniqueModels, function(value) {
        return value != 0
    });

    //console.log(uniqueModels);
}

【讨论】:

    【解决方案2】:

    你做对了,只是一些小的 PHP 调整,你就会得到它。序列化数据并发送到 PHP 后,您始终可以使用 print_r($models) 函数检查该数组的外观。

    要遍历您的 $models 数组,请执行以下操作:

    foreach($models as $model) {
      echo 'Value of hidden input is: ' . $model;
      echo '<br />';
    }

    $model 将表示通过 PHP 请求接收到的实际值。 Check out this example

    【讨论】:

      猜你喜欢
      • 2011-05-21
      • 1970-01-01
      • 2013-06-09
      • 2012-06-11
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2017-11-16
      相关资源
      最近更新 更多