【问题标题】:Jquery autocomplete and PHP: populating input field with data from mySQL database based on selected option in autocomplete fieldJquery 自动完成和 PHP:根据自动完成字段中的选定选项使用来自 mySQL 数据库的数据填充输入字段
【发布时间】:2011-11-16 15:04:32
【问题描述】:

我正在尝试根据用户从 jQuery 自动完成字段中选择的 Suburbs 选项,使用来自 mySQL 数据库的数据填充 Postcode(即邮政编码)输入字段。

自动完成功能正常 - 根据用户输入的术语检索过滤后的郊区列表。源参考是一个 PHP 文件。但是我不知道如何使用用户选择的选项来回调数据库以检索邮政编码。可能可以在第一次调用中检索到邮政编码,同时检索郊区:除了我不想要所有的邮政编码,只想要用户最终选择的那个。

我的 jQuery 如下:("$('#postcodes')" 行还不能工作......)

  <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
  <script type="text/javascript" src="js/jquery-ui-1.8.15.custom.min.js"></script>
  <script>
  // autocomplete
  $(function() {
  $( "#suburbs" ).autocomplete({
  source: "allSuburbs.php",
  minLength: 3,
  select: function( event, ui ) {
  $('#postcodes').val(ui.item.postcode);
  },
  });
  });
  </script>

相关html:

  <p>Suburb</p><input class="inputText" type="text" 
  size="50" name="term" id="suburbs" maxlength="60" /></td>
  <td><p>State</p><input class="inputText" type="text" 
  size="5" name="" id="states"  maxlength="4" /></td>
  <td><p>Postcode</p><input class="inputText" type="text" 
  size="5" name="" id="postcodes" maxlength="4" /></td>

PHP (allSuburbs.php):

  <?php
  $con = mysql_connect("***","***","***");
  if (!$con) { die('Could not connect: ' . mysql_error()); }
  $dbname = 'suburb_state';
  mysql_select_db($dbname);
  $query = "SELECT name FROM suburbs";
  $result = mysql_query($query);
  if (!$result) die ("Database access failed:" . mysql_error());
  //retrieving the search term that autocomplete sends
  $qstring = "SELECT name FROM suburbs WHERE name LIKE '%".$term."%'";
  //query the database for entries containing the term
  $result = mysql_query($qstring);
  //loop through the retrieved values
  while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
  { $row['name']=htmlentities(stripslashes($row['name']));
  $row['postcode']=htmlentities(stripslashes($row['postcode']));
  $row_set[] = $row['name'];//build an array
  }
  echo json_encode($row_set);//format the array into json data
  mysql_close($con);
  ?>

我发现这些链接可能最有帮助:

http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/ (这最初对我有帮助)

http://www.jensbits.com/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/(这是最接近我的问题,尽管它根据州选择使用一系列邮政编码填充邮政编码或邮政编码字段,而不是基于一个郊区/城市的单个邮政编码)。

任何帮助表示赞赏。 非常感谢你, 安德鲁

【问题讨论】:

    标签: php jquery mysql


    【解决方案1】:

    我已经完全将这个功能内置到我的应用程序中。这里还有一层复杂性,因为有两个郊区查找(家庭地址和工作地址),每个都填充匹配的州和邮政编码字段。后端是 perl 而不是 PHP,但这与客户端处理无关。最终,后端会返回一个带有如下哈希数组的 JSON 结构:

    [ { "id":"...", "value":"...", "state":"...", "pcode":"..." }, ... ]
    

    id键包含郊区名称,value键包含像“JOLIET IL 60403”这样的字符串,因此选择了正确的set数据,解决了多个城镇/郊区的问题在不同的地方使用相同的名称,并进行回调以解决该问题。

    选择后,郊区 (id)、州和 pcode 值将被注入到匹配参数中。

    以下代码还缓存以前的结果(并且缓存在家庭和工作查找之间共享)。

    $('#hm_suburb').addClass('suburb_search').attr(
             {suburb: '#hm_suburb', pcode: '#hm_pcode', state: '#hm_state'});
    $('#wk_suburb').addClass('suburb_search').attr(
             {suburb: '#wk_suburb', pcode: '#wk_pcode', state: '#wk_state'});
    var sub_cache = {};
    $(".suburb_search").autocomplete({
        source: function(request, response) {
            if (request.term in sub_cache) {
                    response($.map(sub_cache[request.term], function(item) {
                        return { value: item.value, id: item.id,
                                 state: item.state, pcode: item.pcode }
                    }))
                return;
            }
            $.ajax({
                url: suburb_url,
                data: "term=" + request.term,
                dataType: "json",
                type: "GET",
                contentType: "application/json; charset=utf-8",
                dataFilter: function(data) { return data; },
                success: function(data) {
                    sub_cache[request.term] = data;
                    response($.map(data, function(item) {
                        return {
                            value: item.value,
                            id: item.id,
                            state: item.state,
                            pcode: item.pcode
                        }
                    }))
                } //,
                //error: HandleAjaxError  // custom method
            });
        },
        minLength: 3,
        select: function(event, ui) {
            if (ui.item) {
                $this = $(this);
                //alert("this suburb field = " + $this.attr('suburb'));
                $($this.attr('suburb')).val(ui.item.id);
                $($this.attr('pcode')).val(ui.item.pcode);
                $($this.attr('state')).val(ui.item.state);
                event.preventDefault();
            }
        }
    });
    

    【讨论】:

    • 嗯,重要的是,尽管您对自动完成的 AJAX 调用必须返回 idvalue,但您不仅限于这些属性。我也返回statepostcode,以更改其他表单元素。
    【解决方案2】:

    在您的select 函数中,您将要触发另一个ajax 请求。这个新的 ajax 请求会将当前选择的郊区发送到另一个 php 脚本,该脚本将返回该郊区的邮政编码。在与此 ajax 请求关联的回调中,将返回的邮政编码填写到您的表单中。

    您需要使用 jQuery.get 来触发您的新 ajax 请求: http://api.jquery.com/jQuery.get/

    select: function(event, ui) {
           $.get("postcodes.php", { suburb: $("#suburbs").val },
           function(postCodes) {
             // use data in postCodes to fill in your form.
           }, "json");
    }
    

    postcodes.php 将采用 $_GET['suburb'] 并返回一些包含该郊区邮政编码的 json 结构。

    【讨论】:

      【解决方案3】:

      我想通了。谢谢大家。

      我还发现以下内容与我所追求的非常接近:

      http://af-design.com/blog/2010/05/12/using-jquery-uis-autocomplete-to-populate-a-form/

      相关的jQuery:

        <script type="text/javascript">
        $(document).ready(function(){
          var ac_config = {
          source: "SuburbStatePostcodeRetriever.php",
          select: function(event, ui){
              $("#suburb").val(ui.item.locality);
              $("#state").val(ui.item.state);
              $("#postcode").val(ui.item.postcode);
          },
          minLength:3
          };
              $("#suburb").autocomplete(ac_config);
        });
        </script>
      

      HTML:

        <form action="#" method="post">
       <p><label for="city">Suburb</label><br />
           <input type="text" name="city" id="suburb" value="" /></p>
       <p><label for="state">State</label><br />
           <input type="text" name="state" id="state" value="" /></p>
       <p><label for="zip">Postcode</label><br />
           <input type="text" name="zip" id="postcode" value="" /></p>
        </form>
      

      PHP:

        <?php
        // connect to database
        $con = mysql_connect("********","********","********");
        if (!$con) { die('Could not connect: ' . mysql_error()); }
        $dbname = '********';
        mysql_select_db($dbname);
        $initialSuburbsArray = array( );
        $result = mysql_query("SELECT locality, postcode, state FROM ********",$con) or die (mysql_error());
        while( $row = mysql_fetch_assoc( $result ) ) {
            $initialSuburbsArray[] = $row;
        }
        $suburbs = $initialSuburbsArray;
        // Cleaning up the term
        $term = trim(strip_tags($_GET['term']));
        // get match
        $matches = array();
        foreach($suburbs as $suburb){
      if(stripos($suburb['locality'], $term) !== false){
          // Adding the necessary "value" and "label" fields and appending to result set
          $suburb['value'] = $suburb['locality'];
          $suburb['label'] = "{$suburb['locality']}, {$suburb['postcode']} {$suburb['state']}";
          $matches[] = $suburb;
          }
        } 
        // Truncate, encode and return the results
        $matches = array_slice($matches, 0, 5);
        print json_encode($matches);
        mysql_close($con);
        ?>
      

      可能还需要一些改进,但仅此而已。谢谢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-16
        • 1970-01-01
        • 1970-01-01
        • 2013-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-03
        相关资源
        最近更新 更多