PHP: Unable to get the json output into my javascript page as a variable value [duplicate]

有些话、适合烂在心里 提交于 2019-12-25 01:53:32

问题


i have to get output in this format var sampleTags = ['c++', 'scala'];

My javascript function is:

 <script>
            $(document).ready(function(){
        $(function(){  
             var sampleTags;

            $.ajax({
                url:"<?php echo base_url('ajax_get_tags/gettags'); ?>"
            }).done(function(data) {
                if (data) {
                   sampleTags = data;
                }
            });
       ......................
        .......................



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

My php controller is

   function gettags(){
    $json_array=$this->tagsmodel->get_all_tags(); 
   echo json_encode($json_array); 
 }

My model is

 //-------------------------------Function get all tags--------------------------------
function get_all_tags() { 
    $this->load->database();
    $this->db->limit('10');
    $this->db->select('tags_name');
    $res = $this->db->get('tags');
    $ret = array();

    foreach ($res->result_array() as $row) {
          $ret[] = $row['tags_name'];
    }

    return $ret;
}

How can get the json output from ajax request to be display its value for a javascript variable? Please help me to solve this issue..


回答1:


You're using an older version of jQuery, so .done won't work. It looks like you want to add a key to your request object called complete, with the anonymous function as its value:

$.ajax({
  url: "<?php echo base_url('ajax_get_tags/gettags'); ?>",
  complete: function(data) {
      if (data) {
          sampleTags = data;
      }
  }
});

I found this out by googling your error message. One of the results was this question: Object #<XMLHttpRequest> has no method 'done'. You could have just googled the error message and figured this out yourself.




回答2:


I would like to give a few suggestions

  1. Check for the return value form the server side by printing it with die or exit.
  2. check the http response in firebug net tab. 3.


来源:https://stackoverflow.com/questions/16441838/php-unable-to-get-the-json-output-into-my-javascript-page-as-a-variable-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!