一旦有人从自动完成选项列表中选择了一个项目,我如何将该项目的ID存储为变量以在其他php脚本中使用?
当前 PHP 脚本:
$rs = mysql_query('select label, id from table where label like "'. mysql_real_escape_string($_REQUEST['term']) .'%" order by label asc limit 0,10', $dblink);
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['label'] ,
'value' => $row['id']
);
}
}
echo json_encode($data);
flush();
我的目标是使用 id 变量作为表名的占位符
嗯? Php在服务器上运行,JavaScript/jQuery在客户端上运行。 你不能直接从 JavaScript 设置任何 php 变量。
但是,如果对服务器进行 AJAX 调用并将选定的项 ID 作为参数包含在内,则服务器可以记下选定的 ID(例如,作为当前用户会话的一部分),并在后续请求中回引用它。
用于获取自动完成值 ID 的脚本
<script type="text/javascript">
$(function() {
$('#location').val("");
$("#location").autocomplete({
source: "getLocation.php",
minLength: 1,
select: function(event, ui) {
$('#locationid').val(ui.item.id);
}
});
});
</script>
在隐藏中传递 ID
<form action="" method="post" name="addvendor" id="addvendor">
<label>Location:</label>
<input type="text" name="location" id="location" /><span id="locationInfo"></span>
<input type="hidden" name="locationid" id="locationid" />
</form>
用于获取位置和 ID 值的获取页面
<?php
include('../config/config.php');
$return_arr = array();
/* If connection to database, run sql statement. */
$fetch = mysql_query("SELECT location_id,location_name FROM location where location_name like '" . mysql_real_escape_string($_GET['term']) . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['location_id'];
$row_array['value'] = $row['location_name'];
//$row_array['abbrev'] = $row['country_id'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
注意:包括 js 文件 bootstrap.min.js对于样式
<link rel="stylesheet" href="http://www.jensbits.com/demos/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
有关更多信息,请使用链接http://www.jensbits.com/demos/autocomplete/