JSON PHP Array to Javascript

后端 未结 5 1690
刺人心
刺人心 2020-12-17 04:53

Is it possible to JSON this php array via json_encode? Because this php array is called $data and when i do..

var myJson = 

        
相关标签:
5条回答
  • 2020-12-17 05:12

    Passing PHP JSON to Javascript and reading

    var stuff = <?php print json_encode($datajson); ?>; var arr = new Array(); arr= JSON.parse(stuff); document.write( arr[0].cust_code );

    0 讨论(0)
  • 2020-12-17 05:26

    As @Allendar said you can't embed PHP inside a JS file. You could, however, add a function in your JS file to load the JSON data, and then embed that data in a script tag in your PHP file.

    example.js:

    var loadJsonFromPHP = function(json) {
        console.log(json);
    }
    

    example.php:

    <?php
        $data = array("some", "test", "data");
    ?>
    <html>
        <head>
            <script src="example.js"></script>
            <script>
                loadJsonFromPHP(<?php echo json_encode($data) ?>);
            </script>
        </head>
        <body></body>
    </html>
    

    Edit: this is assuming you only need to get the data into JS once at page load, in which case you can skip making AJAX requests.

    0 讨论(0)
  • 2020-12-17 05:27

    I've never tried to do something like this but I think that you're having issue because json_encode returns a json encoded string. You then need to decode this string on the javascript side of things. Try something like the following:

    var myJson = JSON.parse(<?php echo json_encode($data) ?>);
    console.log(myJson);
    
    0 讨论(0)
  • 2020-12-17 05:29

    JSON can handle any type of array (albeit it will cast associative arrays as objects). The problem you are probably facing is that you are trying to output with PHP when the data is available only on Javascript.

    To clarify: once the page has loaded, PHP cannot do anything. Only javascript can process things on client side, PHP works only on the server and has no knowledge of the state of the client.

    0 讨论(0)
  • 2020-12-17 05:35

    First you need a PHP file on a Apache server somewhere with PHP installed. Make a file like this:

    localhost:8888/myfile.php

    <?php
        $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
    
        echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
    ?>
    

    Then your JavaScript (in this example I use jQuery):

    $.getJSON('http://localhost:8888/myfile.php', function(data) {
        console.log(data);
    });
    

    This should be a start to get PHP arrays in to your JavaScript.

    0 讨论(0)
提交回复
热议问题