Passing PHP JSON to [removed] echo json_encode vs echo json declaration

后端 未结 9 2173
猫巷女王i
猫巷女王i 2021-01-05 01:52

I\'m trying to create a common constants file to share between php and javascript, using JSON to store the constants. But I\'m wondering why pass the JSON from PHP to javasc

相关标签:
9条回答
  • 2021-01-05 02:07

    It all depends on what you want to send from server to the client - be it a data (JSON) or some code.

    Two approaches:

    1. Echo a JSON file on a server - then you print your JSON document and set response Content-Type to application/json. This way you can use any AJAX library you wish, like $.get or raw XMLHttpRequest etc. It is a way of passing data.

    2. Echo a Javascript code on a server and then use $.getScript to load it. It's a way of passing code. This is potentially less secure, because your code can contain not only JSON, but also any arbitary code. So if attacker can compromise your server, he could be able to push code to any client for a remote execution.

    If you want to pass data only, go with first approach. It's cleaner and more safe.

    Additionally, if you ever end up writing frontend in different environment, say different programming language, you'll be able to resuse the same JSON-returning endpoint. It'll be harder if you return Javascript code.

    0 讨论(0)
  • 2021-01-05 02:13

    constant.php

    <?php
    $array = array("const1" => "val", "const2" => "val2");
    ?>
    <script>
    var contants = <?php echo json_encode($array); ?>
    </script>
    

    ======================END OF FILE constant.php=======

    In php you can access using

    $array["<key>"]
    

    In javascript, you can access using

    contants.const1, ....
    
    0 讨论(0)
  • 2021-01-05 02:15

    You use json_encode if you use php array not a string:

    $array = array("const1" => "val", "const2" => "val2");
    
    echo json_encode($array);
    

    if you call json_encode on a string you will get:

    "{\"const1\": \"val\", \"const2\": \"val2\"}"
    
    0 讨论(0)
提交回复
热议问题