开发者

Having problems with jQuery UI Autocomplete

开发者 https://www.devze.com 2023-02-07 02:40 出处:网络
I\'m try开发者_如何转开发ing to use the new autocomplete function in jQuery UI, but I\'m having some problems.

I'm try开发者_如何转开发ing to use the new autocomplete function in jQuery UI, but I'm having some problems.

I'm able to retrieve data from the DB (I can see it in FireBug), but I'm not able to display the dropdown list (or alert the data).

This is my jQuery code:

  jQuery('#brand_search').autocomplete({
            source: "http://mysite.com/wp-content/themes/storelocator/include/jquery.search.php?instance=brand",
            minLength: 2,
            delay: 50,
            select: function(e, ui) {
              alert(ui);
            }
        });

And this is my PHP code:

/* ------------------ Brand Autosuggest ------------------------- */
  function autosuggestBrand($dal)
  { 
    $result = $dal->getRowBySearch('sl_label','name', $this->term);   
    $brands = array();

    if(mysql_num_rows($result)>0) 
    {
      while($row = mysql_fetch_assoc($result)) 
      {
          array_push($brands, array(
            "id"      => $row['id'], 
            "name"    => html_entity_decode($row['name'], ENT_QUOTES, 'UTF-8') )
        );
      }     
    }
    echo json_encode($brands);          
  }

I've see these two guides:

http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql

http://net.tutsplus.com/tutorials/javascript-ajax/how-to-use-the-jquery-ui-autocomplete-widget

But still can't quite figure out how to display / alert the fetched data.

This is the result from echo json_encode

[
  {"id":"4642","name":"Mo Koshji"},
  {"id":"4627","name":"MO-A"},
  {"id":"4626","name":"MO'CYCLE"},
  {"id":"4628","name":"mo851"},
  {"id":"4629","name":"Mob Action"}
]


correct your php array with the following in order to get a correct json output for jquery-autocomplete:

array_push
(
   $brands,
   array
   (
      "label"  => $row['id'], 
      "value"  => html_entity_decode($row['name'], ENT_QUOTES, 'UTF-8') )
    );
);

because jquery autocomplete needs those json property names to run the autocomplete as specified on the documentation:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu.

http://jqueryui.com/demos/autocomplete/#custom-data


change your code to this (take it out of the click event handler):

jQuery(function()
{  
 jQuery('#brand_search').autocomplete({
        source: "http://mysite.com/wp-content/themes/storelocator/include/jquery.search.php?instance=brand",
             minLength: 2,
             delay: 50,
             select: function(e, ui) {
               alert(ui);
              }         
 }); 
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号