how to get data to javascript from php using json_encode?

后端 未结 7 2041
梦如初夏
梦如初夏 2020-12-29 12:20

I am trying to map traceroutes to google maps.

I have an array in php with traceroute data as

$c=ip,latitude,longitude, 2nd ip, its latitude, longitu         


        
相关标签:
7条回答
  • 2020-12-29 12:35

    I could get the JSON array by using PHP's json_encode() from backend like this example:

    <!doctype html>
    <html>
        <script type="text/javascript">
            var json = <?php echo json_encode(array(1 => '123', 'abc' => 'abd', 2 => 5));?>;
            console.log(json[1]);
            console.log(json.abc);
        </script>        
    </html>
    

    No quotation marks means an eval() of whatever was printed out. This is a quick hack that we utilised often to quickly add initial values to our AJAX page.

    0 讨论(0)
  • 2020-12-29 12:37

    HTML

    <select name="sub" id="subcat" class="form-control" required="required">
    
    </select>
    

    PHP

    $this->load->model('MainModel');
    $subvalue = $this->MainModel->loadSubData($var);
    echo json_encode($subvalue);
    //if MVC
    // or you can just output your SQLi data to json_encode()
    

    JS

    $("#maincat").change(function(){
      var status = this.value;
    
      $.ajax({
        type: 'POST',
        url: 'home/subcat/'+status,
        success: function(data){
            var option = '';
            var obj = JSON.parse(data);
            if(obj.length > 0){
                for (var i=0;i<obj.length;i++){
                option += '<option value="'+ obj[i].id + '">' + obj[i].name + '</option>';  
                }
                //Now populate the second dropdown i.e "Sub Category"
                $('#subcat').children("option").remove();
                $('#subcat').append(option);
            }else{
                option = '<option value="">No Sub Category Found</option>';
                $('#subcat').children("option").remove();
                $('#subcat').append(option);
            }       
        },
        error: function(){
        alert('failure');
        }
    });
    
    0 讨论(0)
  • 2020-12-29 12:41

    This function works for you I guess:

        function json_encode4js($data) {
        $result = '{';
        $separator = '';
        $count = 0;
        foreach ($data as $key => $val) {
    
            $result .= $separator . $key . ':';
            if (is_array($val)){
                $result .= json_encode4js($val).(!$separator && count($data) != $count ? ",":"");
                continue;
            }
            if (is_int($val)) {
                $result .= $val;
            } elseif (is_string($val)) {
                $result .= '"' . str_replace('"', '\"', $val) . '"';
            } elseif (is_bool($val)) {
                $result .= $val ? 'true' : 'false';
            } elseif (is_null($val)) {
                $result .= 'null';
            } else {
                $result .= $val;
            }
    
            $separator = ', ';
            $count++;
        }
    
        $result .= '}';
    
        return $result;
    }
    
    $a = array(
    "string"=>'text',
    'jsobj'=>[
        "string"=>'text',
        'jsobj'=>'text2',
        "bool"=>false
        ],
    "bool"=>false);
    
    var_dump( json_encode4js($a) ); //output: string(77) "{string:"text", jsobj:{string:"text", jsobj:"text2", bool:false}, bool:false}" 
    
    var_dump( json_encode($a));//output: string(85) "{"string":"text","jsobj":{"string":"text","jsobj":"text2","bool":false},"bool":false}"
    
    0 讨论(0)
  • 2020-12-29 12:48

    I know this is old, but I recently found myself searching for this. None of the answers here worked for my case, because my values had quotes in them. The idea here is to base64 encode the array before echo'ing to the page. That way the quotes don't conflict.

    < ?php
    $names = ['first' => "some'name"];
    ?>
    var names = JSON.parse(atob('< ?php echo base64_encode(json_encode($names)); ?>'));
    console.log(names['first']);
    
    0 讨论(0)
  • 2020-12-29 12:51

    I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.

    For parsing JSON, simply do

    var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );
    

    You can now access everything easily:

    alert ( obj.name );
    

    Note: jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval () method.

    Edit: To get data from the server side to the client side, there are two possibilities:

    1.) Use an AJAX request (quite simple with jQuery):

       $.ajax ( {
           url: "yourscript.php",
           dataType: "json",
           success: function ( data, textStatus, jqXHR ) {
               // process the data, you only need the "data" argument
               // jQuery will automatically parse the JSON for you!
           }
       } );
    

    2.) Write the JSON object into the Javascript source code at page generation:

       <?php
           $json = json_encode ( $your_array, JSON_FORCE_OBJECT );
       ?>
    
       <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
    
       <script type="text/javascript">
       //<![CDATA[
    
       var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );
    
       //]]>
       </script>
    
    0 讨论(0)
  • 2020-12-29 12:53

    no need for jquery, just:

        var array= <?php echo json_encode($array); ?>;
        console.log(array->foo);
    
    0 讨论(0)
提交回复
热议问题