实时搜索获得多个字段

时间:2015-02-16 06:41:28

标签: php jquery ajax json postgresql

我有这个实时搜索,它完美无缺。我想做的是我想得到另一个领域。除了获取indcator名称之外,我还希望通过使用实时搜索单击指示符名称将其分配给另一个输入类型来获取其ID。

Heres the Script:

  <script type="text/javascript">
       $(document).ready(function() {
       $('#indicatorname').autocomplete({
           source: function( request, response ) {
           $.ajax({
             url : 'ajax.php',
             dataType: "json",
        data: {
           name_startsWith: request.term,
           type: 'indicatorname'
        },
         success: function( data ) {

           response( $.map( data, function( item ) {
            return {
              label: item,
              value: item
            }
          }));  


         }
          });
        },
        autoFocus: true,
        selectFirst: true,
        minLength: 0,
        focus : function( event, ui ) {
         $('#indicatorname').html(ui.item.value);
        },
        select: function( event, ui ) {
         $('#indicatorname').html(ui.item.value);
        },
        open: function() {
         $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top");
        },
        close: function() {
          $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }           
         });

     $('#slider').rhinoslider({
        effect: 'transfer'
      });
        });
   </script>

继承人ajax.php:

  <?php

   $connection = pg_connect("host=localhost dbname=brgy_profiler
                 user=postgres password=password");

    if (!$connection)
         {  
          echo "Couldn't make a connection!";
         }

  ?>

<?php

    if($_GET['type'] == 'indicatorname'){
     $result = pg_query("SELECT cindicatordesc,nindicatorid from
                          tbl_indicators where cindicatordesc LIKE
                          '%".$_GET['name_startsWith']."%'");   
     $data = array();
    while ($row = pg_fetch_array($result)) 
       {
         array_push($data, $row['cindicatordesc']);
       }    

        echo json_encode($data);
     }

  ?>

这是我的tbl_indicator:

enter image description here

我如何获得 nindicatorid 字段并使用ajax实时搜索与 cindicatordesc 一起使用?

注意:只显示cindicatordesc,nindicatorid将保存在输入类型中。

1 个答案:

答案 0 :(得分:1)

不是问题。您可以在自动完成select返回时添加其他数据属性,

 $('#indicatorname').autocomplete({   
         source: function( request, response ) {
         ...........
         success: function( data ) {
           response( $.map( data, function( itemList ) {
            return {
              label: itemList.label,
              value: itemList.value,
              extraField : itemList.extraField
                }
          }));

因此,只需更改您需要的服务器端,您需要将额外值发送到自动完成AJAX。

并且,在select事件中,您可以将值提取为ui.item.extraField

这是使用多个属性的Sample Demo。虽然它和你做的不一样,但内在逻辑是一样的。

相关问题