带有php和ajax的POST JSON数组-问题

时间:2019-02-04 14:28:43

标签: php json ajax

我不明白如何通过脚本(下面)传递使用php创建的“操作”变量和“产品”数组。

<?php
   $actionFile = "add";
   $products = array("Name product", "price", "sku", ....);
?>
<script>
    function uploadProducts() {
        var formData = new FormData();
        formData.append("action", <?php echo json_encode($actionFile); ?>);
        formData.append("products", <?php echo json_encode($products); ?>);

        $.ajax({
            type: 'POST',
            url: './controllers/uploadProductsController.php',
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function(){
                // Show image container
                //$("#loader").show();
                console.log("1");
            },
            success: function(response){
                //$('.response').empty();
                //$('.response').append(response);
                console.log("2");
                console.log(response);
            },
            complete: function(){
                // Hide image container
                //$("#loader").hide();
                console.log("3");
            }
        });            
    }
</script>

uploadProductsControlle.php(以下代码)我将数组打印为单个字符串,而不打印为数组。

<?php
    include("../../functions.php");

    $action = $_POST['action'];
    $productsArr = $_POST['products'];
    $response = array();

    var_dump(json_encode($productsArr));  //ERROR THIS PRINT STRING

    foreach($productsArr as $product) {
        echo $product;
    }
    ?>

我需要将“产品”作为数组来进行循环。 谢谢

1 个答案:

答案 0 :(得分:0)

您应该使用json_decode函数

git replace