dryk50495
2014-07-27 16:19
浏览 64
已采纳

使用AJAX调用在自动完成中将变量值从一个函数传递到另一个函数

I have a problem in using autocomplete jQuery with AJAX call. When user types something in input field, I post that value with AJAX to controller where I get the values from database and then all these values to the JavaScript in success message. But after that, I'm having problem to use these JSON values for autocomplete. How to fix that?

The view file

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>         
          $(function() {

             $("#tags").autocomplete({     
                 source: function( request, response ) {  
                 $.ajax({
                          type: "POST",
                          url: "<?php echo base_url().'index.php/search_con/user' ;?>",
                          data: {'userA': request.term}, 
                   success: function(msgs)
                          {
                          var a = ["Central Palms Hotel","Hotel Monalisha","asghgjfddas","My hotel added","asdfsdf","asdsadsa"];  

                        response(a);
                         // alert(msgs);
                          }
                 });  
                  }

              });

           });


        </script>


<div class="ui-widget">
  <label for="tags">Tags:</label>
  <input id="tags">
</div>

and the controller

public function user(){

  $userPart = $_POST['userA'];      

  $result = $this->searchdb->search($userPart) ;

  $list = array();

  foreach ($result as $finaldata) {
    $data= $finaldata->name;
    array_push($list, $data);
  }

  echo json_encode($list); 
} 

Now my problem is that when i remove static variable a and use msgs for response nothing is shown in autocomplete data and when alert msgs i get the same data as in variable a. is there any mistake in my json?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • doudou1897 2014-07-28 06:03
    最佳回答

    You don't need to have separate function to fetch the data for autocomplete, can be done like this

    $(function () {
        $("#tags").autocomplete({
            source: function (request, response) {
                $.post("<?php echo base_url().'index.php/search_con/user' ;?>", {
                    userA: request.term
                }, response);
            }
        });
    });
    

    And because of the async nature of ajax you cant do this

    $.ajax({
        type: "POST",
        url: "<?php echo base_url().'index.php/search_con/user' ;?>",
        data: dataString,
        success: function (msgs) {
            data = msgs;
        }
    });
    
    alert(data); // undefined
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题