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

后端 未结 9 2172
猫巷女王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 01:54

    In your case $json_obj is already a string. So it is not necessary. But if you have an array you want to pass to javascript json_encode will help you with this.

    0 讨论(0)
  • 2021-01-05 01:55

    Usually this is what I do, the safest way I've found:

    // holds variables from PHP
    var stuff = {};
    try {
        // stuff will always be an object
        stuff = JSON.parse('<?php echo empty($stuff) ? '{}' : json_encode($stuff) ?>');
    } catch (e) {
        if (e instanceof SyntaxError)
        {
            // report syntax error
            console.error("Cannot parse JSON", e);
        }
    }
    // show resulting object in console
    console.log("stuff:", stuff);
    
    0 讨论(0)
  • 2021-01-05 01:58

    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)
  • 2021-01-05 01:58

    json_encode is a function that converts a PHP array into a JSON string, and nothing more. Since your $json_obj variable is already a JSON string, no further conversion is needed and you can simply echo it out.

    To get to your $json_obj string from an array your code would have looked like this

    $json_array = array(
        "const1" => "val",
        "const2" => "val2"
    );
    
    $json_obj = json_encode($json_array);
    
    0 讨论(0)
  • 2021-01-05 02:00

    Even though it may seem like overkill for your particular problem, I would go for the json_encode/parse option still. Why? you ask. Well, think of it as avoiding duplication. If you encode/parse you can keep the constants in an object easily readable by you PHP-code. And the same for your JS code.

    It simply eliminates the need to fiddle with it.

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

    The argument to json_encode() should be a PHP data structure, not a string that's already in JSON format. You use this when you want to pass a PHP object to Javascript.

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