我有一个表单,它包含以下几种类型的元素
<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
}
但这不起作用。我做错了什么?
我最终在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);
}
如果你做得正确,只需对PHP进行一些小的调整,你就会得到它。一旦你序列化了数据并将其发送到PHP,你就可以使用print_r($models)
函数来检查数组的外观。
要在$models
阵列中循环,请执行以下操作:
foreach($models as $model) {
echo 'Value of hidden input is: ' . $model;
echo '<br />';
}
$model
将表示通过PHP请求接收到的实际值。查看此示例