【问题标题】:How to access an array outside if? I use ajaxif如何访问外部数组?我用ajax
【发布时间】:2019-05-17 09:06:40
【问题描述】:

我通过 ajax (1, 2, 3, 4) 发送数据并尝试将它们写入“pColors”数组。问题是我无法访问数组。 我做了测试,确认数据到达 $_POST 但没有记录在数组中。

$x = $getProductID;
$_SESSION['pColors'] = array();

if(isset($_POST['pColors'])) {  

   foreach($_POST['pColors'] as $colorKey => $RColors) {

      $_SESSION['pColors'][$x][$colorKey] = $RColors;   

    }
}

$x 获取产品 ID 我用它们作为密钥

关于这是什么原因的任何想法? Тhanks !

                $('.addToCart').click(function(){
                    $.ajax({
                        url:""+realLink+"cart.php",
                        method:"POST",
                        data:{pColors:pColors},
                            success:function(data){
                               //alert(pColors);
                               //console.log(this.data);
                            }
                    });
                });

【问题讨论】:

  • 为什么你使用 $_SESSION 而不仅仅是一个简单的数组来返回你的 ajax 以在成功时使用?您也可以向我们提供您的 ajax 调用吗?
  • 如何恢复到ajax?使用success:function(data){ alert(data); } ?
  • 如果是函数或 print_r(),则返回它;它 。如果您打印/回显结果,JS 会选择它
  • session_start()?你返回数组吗?
  • @dWinder 是打开php标签后立即添加的

标签: php arrays ajax


【解决方案1】:

所以不知道我怎么没早点看到这个,但是你的 pColors javascript 变量是在调用 ajax 的函数之外定义的,你在那里发送空数据。

我将您的脚本修改为以下内容:

<script>
filter_data();

function filter_data() {

    var action = 'fetch_data';


    $('.addToCart').click(function(){

        var pColors = document.getElementById("pColors").value
        $.ajax({
            url:"http://samplesite/devsite/ajax.php",
            method:"POST",
            data:{ pColors : pColors },
                success:function(data){
                console.log(data);
}
        });
    });

}
    </script>

在我的开发服务器上测试,它输出以下内容:

数组
(
    [pColors] => 1,2,3,4
)

编辑:

还需要把ajax php文件改成如下:

$x = $getProductID;
$_SESSION['pColors'] = array();



    if(isset($_POST['pColors'])) {  
        foreach($_POST as $colorKey => $value) {
            if ($colorKey == 'pColors') { 


            $_SESSION['pColors'][$colorKey] = $value;
        }
        }

    }

    echo '<pre>';
    print_r($_SESSION['pColors']);
    echo '</pre>';

您会注意到 foreach 现在正在 $_POST 方法本身上运行,并使用 if 语句检查它是否是正确的键。

我现在添加了:

$colorFolder = "Placeholder Folder";

$getColorTitle = array("uniqueID" => "2");

$rowColors = array("image" => "Placeholder Image");


echo '
                                  <li>
                                  <input type="hidden" class="getColorID" id="'.$getColorTitle['uniqueID'].'" />
                                  <input type="checkbox" name="pColors" class="css-checkbox pColor" value="'.$getColorTitle['uniqueID'].'" id="cb-'.$getColorTitle['uniqueID'].'"/>
                                    <label for="cb-'.$getColorTitle['uniqueID'].'"><img src="'.$colorFolder.''.$rowColors['image'].'" height="50px" />
                                <div class="colorsC">
                                <input type="hidden" value="0" style="width: 45px;" class="qtyC" />
                                    <input type="button" value="0" style="width: 45px;" class="qtyC addToCart" />
                                </div>
                                    </label>
                                  </li>';

                                  ?>

哪个输出:

test.php:117 <pre>Array
(
    [] => Array
        (
            [pColors] => Array
                (
                    [0] => 2
                )

        )

)
</pre>

哪个是正确的 ID

--- cart.php ----

<?php


$_SESSION['pID'] = "9";

$_SESSION['pQua'] = "20";


if(isset($_SESSION['pID']) && isset($_SESSION['pQua'])) {
    foreach($_SESSION as $getProductID => $valueTwo) {
        if ($getProductID == "pID")   {
        $x = $getProductID;
        $_SESSION['pColors'] = array();

if(isset($_POST['pColors'])) {
    foreach($_POST as $colorKey => $value) {
        if ($colorKey == 'pColors') { 
            $_SESSION['pColors'][$x][$colorKey] = $value;
        }
    }
}

    }
}
}

            echo '<pre>';
            print_r($_SESSION['pColors']);
            echo '</pre>';


?>

--product.php ---

<?php

include_once 'header.php';

$colorFolder = "Placeholder Folder";

$getColorTitle = array("uniqueID" => "2");

$rowColors = array("image" => "Placeholder Image");


echo '
                                  <li>
                                  <input type="hidden" class="getColorID" id="'.$getColorTitle['uniqueID'].'" />
                                  <input type="checkbox" name="pColors" class="css-checkbox pColor" value="'.$getColorTitle['uniqueID'].'" id="cb-'.$getColorTitle['uniqueID'].'"/>
                                    <label for="cb-'.$getColorTitle['uniqueID'].'"><img src="'.$colorFolder.''.$rowColors['image'].'" height="50px" />
                                <div class="colorsC">
                                <input type="hidden" value="0" style="width: 45px;" class="qtyC" />
                                    <input type="button" value="0" style="width: 45px;" class="qtyC addToCart" />
                                </div>
                                    </label>
                                  </li>';

                                  ?>

--- ajaxCart.js ---

<script>filter_data();

function filter_data() {

    $('.addToCart').click(function(){

        var pColors = get_filter('pColor');

        $.ajax({
            url:"http://samplesite/devsite/ajax2.php",
            method:"POST",
            data:{ pColors : pColors },
                success:function(data){
                   //alert(pColors);
                   console.log(data);
                }
        });
    });

}

function get_filter(class_name) {
    var filter = [];
    $('.'+class_name+':checked').each(function(){
        filter.push($(this).val());
    });

    if($('.'+class_name+'').is(':checked')){
        $('.colorsC').find('input:hidden').each(function() {
           $("<input type='text' />").attr({ style: 'width: 45px;', value: this.value }).insertBefore(this);
        }).remove();                    
    } else {
        $('.colorsC').find('input:text').each(function() {
           $("<input type='hidden' />").attr({ style: 'width: 45px;', value: '0' }).insertBefore(this);
        }).remove();
    }

    return filter;
}

$('.css-checkbox').click(function(){
    filter_data();
   });

$('.addToCart').click(function(e) {
    e.preventDefault();

    productID = $(this).attr('id');
    productQuantity = $('#productID'+productID+'').val();

    $.post('http://samplesite/devsite/ajaxAddProduct.php', {
        pID: productID,
        pQua: productQuantity,
    }, function(response){
        $('#successID'+productID+'').show('slow');
    });
    alert('Успешно добавихте продукта в количката');
    setTimeout(function() {
        $('#successID'+productID+'').hide('slow');

    }, 1000);

    return false;
});

</script>

【讨论】:

  • 谢谢!我按照您的描述尝试了代码,但由于某种原因,我得到了一个空数组。
  • 我在我的代码中调用了 var pColors = document.getElementById("pColors").value,您可能想确保它不在您的代码中,需要改回 var pColors = get_filter('pColor');
  • 是的,当我在突出显示颜色时发送值时立即更改了它。 ...我开始认为它与其余代码有关。我贴了整个js github.com/eSportBG/colors/blob/master/code
  • 这是我使用您的过滤器和复选框而不是文档 id:test.php:116
    Array ( [] => Array ( [pColors] = > 数组 ( [0] => on ) ) ) 
  • lol.. 我怎样才能让它在标记颜色时发送正确的数据?
猜你喜欢
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
相关资源
最近更新 更多