php : how to pass database value into a javascript

2019-03-02 08:07发布

问题:

I am implementing tags feature in my project. In my demo tags i found they are passing names in a javascript function for the autocomple.

This is a function in my demo project,

   <script>
   $(function()
      {
          var sampleTags = ['c++', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
      ..................
      .................

So , i want pass values from my php controller to this function ,inorder to get the autocomplete value from my database table

For example i am getting tags values from my db in my Controller like this:

 ` $data["query"] = $this->ordermodel->fetch_orderlist();`
   $this->load->view('tagpage', $data);  //loading my page tag page where above function exists

Now how can i pass that $data["query"] values into the above javascript function? Please help

回答1:

You could echo the variable onto the page using PHP's json_encode. This function will convert a PHP array or object into a JSON object, which JavaScript can work with:

<script>
$(function() {
      var sampleTags = <?php echo json_encode($query); ?>;
})();
</script>

But a better way would be to request these values via Ajax. Say you have a PHP script named values.php:

<?php
    #...
    #assign $query here
    #...
    echo json_encode($query);

Then, in JavaScript (on the page where you want to use the sampleTags variable), you can use jQuery's .ajax function to make an easy Ajax request:

<script>
var sampleTags;

$.ajax({
    url: 'values.php'
}).done(function(data) {
    if (data) {
       sampleTags = data;
    }
});
</script>

I haven't tested this example. Obviously you'll want to tweak it to fit your environment.



回答2:

You will have to write an ajax function for this

$.ajax(
    url     :   "<?php echo site_url('controller/method')?>",
    type    :   'POST',
    data    :   'para=1',
    success :   function(data)
    {
        if(data){
            var sampleTags  =   data;
        }
    }
);


回答3:

Just echo your php variable

 $(function()
      {
          var sampleTags = '<?php echo $data["query"]; ?>'