jQuery自动完成PHP Mysql张贴不同的字段

jQuery Autocomplete PHP Mysql posting different field

本文关键字:张贴不 字段 Mysql PHP jQuery      更新时间:2023-09-26

我正在使用jQuery的自动完成,我正在用一个名为site.php的php文件填充我的自动完成下拉列表。php从名为site的mysql表中获取值,该表有3列:id, codesite。我希望我的自动完成只显示codesite,然后将相应的id存储在我的另一个表中。

一切都很好,除了自动完成是发布codesite选择,而不是id。为了将id发送到我的php POST而不是codesite,我需要改变什么?脚本如下:

PHP文件:site.php

<?php
        $server = 'sql203.com';
        $user = 'xxxxxxxxxxxx';
        $password = 'xxxxxxx';
        $database = 'b17';
    $mysqli = new MySQLi($server,$user,$password,$database);
    /* Connect to database and set charset to UTF-8 */
    if($mysqli->connect_error) {
      echo 'Database connection failed...' . 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
      exit;
    } else {
      $mysqli->set_charset('utf8');
    }
    /* retrieve the search term that autocomplete sends */
    $term = trim(strip_tags($_GET['term'])); 
    $a_json = array();
    $a_json_row = array();
    if ($data = $mysqli->query("SELECT * FROM `b17_16413362_upupa`.`site` WHERE code LIKE '%$term%' OR site LIKE '%$term%' ORDER BY code , site")) {
        while($row = mysqli_fetch_array($data)) {
            $id = htmlentities(stripslashes($row['id']));
            $code = htmlentities(stripslashes($row['code']));
            $site = htmlentities(stripslashes($row['site']));
            $a_json_row["id"] = $id;
            $a_json_row["value"] = $code.' '.$site;
            $a_json_row["label"] = $code.' '.$site;
            array_push($a_json, $a_json_row);
        }
    }
    // jQuery wants JSON data
    echo json_encode($a_json);
    flush();
    $mysqli->close();
    ?>
Javascript:

<script type="text/javascript">
$(function() {
  $("#sitex").autocomplete({
    source: 'site.php',
     minLength: 0
        }).focus(function(){     
             $(this).autocomplete("search");
  });
});
</script>

在PHP中修改

$a_json_row["value"] = $code.' '.$site;

$a_json_row["value"] = $id;

value属性是表单将要提交的数据。'label'属性将显示给用户。