PHP arrays into javascript arrays

前端 未结 6 509
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 01:41

I am a bit confused here on how I implement an array into JS from PHP....

I\'m doing this for testing - eventually I\'ll use long polling or websockets if they get h

相关标签:
6条回答
  • 2021-01-17 02:02

    Not sure why you need to wrap the json string in an Array, you could just do

    var data = <?php echo $data; ?>;
    

    --

    To get the value of data in your js, you can either do data.x or data["x"]

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

    You should try this instead:

    var data = <?= $data ?>
    
    0 讨论(0)
  • 2021-01-17 02:09

    You can use AJAX (much easier). Make your PHP script echo $data, and then using jQuery ajax request the data in your HTML file as JSON. For example:

    $.ajax({
        url: script_url,
        dataType: 'json',
        success: function(json)
        {
             ...
        }
    });
    
    0 讨论(0)
  • 2021-01-17 02:27

    I agree with the answer in your comments. I would make an AJAX call to yourFile.php and then send back your JSON encoded response. so here would be my psuedo code.

    1. Make AJAX request
    
    $.ajax({
        url: "yourFile.php",
        dataType: 'json',
        success: function(data)
        {
             console.log(data);
        }
    });
    
    2. Make sure that your PHP file also returns header for JSON
    
    header('Content-type: application/json');
    
    2. Return {"x":"283","y":"99","sid":"1"} as data on your ajax request
    
    
    3. call the values by using data.x or data.y or data.sid
    
    0 讨论(0)
  • 2021-01-17 02:28

    Be sure you're echoing the PHP data into the <script> tags

    <script>var data = Array(<?php echo $data; ?>)</script>
    

    As an aside, it's a good idea to avoid using short tags (<? and ?>) in a production setting--many servers have them disabled by default, and it's a really annoying way to have your code break.

    0 讨论(0)
  • 2021-01-17 02:28

    Not sure if <? $data; ?> is a typo or not but you should be using either <?=$data;?> or <?php echo $data; ?>

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