簡體   English   中英

jQuery自動完成和PHP:根據自動完成字段中的選定選項,使用來自mySQL數據庫的數據填充輸入字段

[英]Jquery autocomplete and PHP: populating input field with data from mySQL database based on selected option in autocomplete field

我試圖根據用戶從jQuery自動完成字段中選擇的Suburbs選項,使用mySQL數據庫中的數據填充郵政編碼(即zipcode)輸入字段。

自動完成功能可以正常工作-根據用戶輸入的條件檢索過濾后的郊區列表。 源引用是一個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/ (這與我的問題最接近,盡管它會根據州選擇以一系列郵政編碼來填充郵政編碼或郵政編碼字段,而不是根據一個郊區/城市來填充一個郵政編碼)。

任何幫助表示贊賞。 謝謝你,安德魯

我已經完全將此功能構建到我的應用程序中。 這里有一個額外的復雜性層,因為有兩個郊區查找(家庭和工作地址),每個查找都填充匹配的州和郵政編碼字段。 后端是perl而不是PHP,但這與客戶端處理無關。 最終,后端將返回帶有以下哈希表數組的JSON結構:

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

id鍵包含郊區名稱,而value鍵包含諸如“ JOLIET IL 60403”之類的字符串,因此一次選擇了正確的數據 ,從而解決了在不同地方具有相同名稱的多個城鎮/郊區的問題,並進行了呼叫-backs解決。

選擇后,將郊區(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();
        }
    }
});

在您的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結構,其中包含該郊區的郵政編碼。

我想到了。 謝謝你們。

另外,我發現以下內容與我所追求的非常接近:

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);
  ?>

可能需要更多改進,但這僅是大部分。 謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM