Foreach无法在php和Jquery中工作


Foreach not working in php and Jquery

我正试图在php和jquery中对多选进行foreach循环,但我要回显的只是Array。

html

<select multiple="multiple" class="select tagz" required>

php

if(!empty($_POST['tagz'])){
            $tag = $_POST['tagz']);
            foreach($tag as $tagz){
            echo $tagz;
            }
        }else{
            echo "Please select tags";
        }

Jquery

function serealizeSelects (select)
        {
            var array = [];
            select.each(function(){ array.push($(this).val()) });
            return array;
        }
        var tagz = serealizeSelects($(".tagz"));
$.post('upload.php', {tagz:tagz, title:title, category:category, description:description, price:price}, function(data){
            $('#confirm').html(data);
        });

请告诉我我做错了什么

您正在执行select.each(function(){ array.push($(this).val()) });但是select变量只包含select元素,并且每个元素都没有意义。您需要在选项中使用each。因此,请更改您的选择器。

           var tagz = serealizeSelects($(".tagz option"));

或者,如果你不想更改选择器,只需使用find来查找所选中的所有选项

           select.find('option').each(function(){ array.push($(this).val()) })

当然,我不知道你在哪里定义你的其他变量。如果你也有其他问题,只需向我展示你的全部javascript代码,这样我就能为你提供更多帮助。

您正试图为名为tagz的字段获取一个post变量,但您没有名为tagz的字段(至少在您提供的代码中没有)。

考虑将HTML更改为:

<select name="tagz" multiple="multiple" class="select tagz" required>