代码之家  ›  专栏  ›  技术社区  ›  夏期劇場

PHP:将键值数组的JSON传递给Javascript:via Ajax vs direct echo out

  •  -1
  • 夏期劇場  · 技术社区  · 6 年前

    为什么通过Ajax向Javascript传递PHP键值数组与直接向Javascript变量发出回声不同?

    下面是一个例子:

    <?php
    $fruits = array(
        "a"=>"apple",
        "b"=>"banana",
        "c"=>"coconut",
    );
    
    if ( isset($_GET["ajax"]) ) {
        header('Content-Type: application/json');
        echo json_encode( $fruits );
        exit;
    }
    ?>
    
    <html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
    
        var fruits_php = <?php echo json_encode($fruits); ?>; //<--NO AJAX (Problem is here!)
        console.log( "PHP:", fruits_php );
    
        jQuery( document ).ready(function() {
            $.ajax({
                url: '?ajax',
                type: "GET",
                cache: false,
                headers: {
                    'Content-Type':'application/json; charset=utf-8',
                    'Cache-Control':'no-cache',
                },
                success: function(fruits_ajax){
                    console.log( "Ajax:", fruits_ajax );  //<--AJAX
                }
            });
        });
    </script>
    </head>
    </html>
    

    然后他们变得不同了:

    enter image description here

    基本上 “钥匙”不见了 在PHP->Javascript直接分配方法中。

    • 为什么会这样?
    • 如何在不丢失原始PHP数组结构的情况下直接分配到Javascript?
    3 回复  |  直到 6 年前
        1
  •  1
  •   ngearing    6 年前

    虽然我不能复制你的例子,但我确实有一些想法。看起来 json_encode 正在将关联数组转换为索引数组。

    可以尝试将数组转换为对象:

    $fruits = (object) array(
        'a' => 'apple',
        'b' => 'banana',
        'c' => 'coconut',
    );
    

    或在 json编码 功能:

    json_encode( $fruits, JSON_FORCE_OBJECT );
    

    你在运行什么版本的php?

        2
  •  0
  •   chethan    6 年前

    尝试JSON.parse(),如下所示

    var fruits_php = JSON.parse(<?php echo json_encode($fruits); ?>);
    
        3
  •  -1
  •   Rahul Kalal    6 年前

    从ajax请求中删除header参数,然后像这样执行控制台日志

    console.log( fruits_ajax );