wil*_*iam 2 php ajax bootstrap-typeahead
我使用Twitter Bootstrap Typeahead作为自动完成字段.
结束状态目标:用户首先在字段1中输入详细信息.当他们在字段2中输入详细信息时,ajax将查询传递给PHP文件,该文件根据也输入到字段1中的内容查询数据库.
如何将字段2中的查询和字段1的内容传递给PHP文件并访问它们.
这是我到目前为止:
HTML文件:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
PHP文件:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
Run Code Online (Sandbox Code Playgroud)
此时,查询部分工作正常并返回结果(控制台还显示来自'Field1'的值.只需要同时将该值放入php文件中!
任何帮助都会很棒
如果我理解正确,你想要将字段1和2的值都解析为同一个AJAX调用.这就是你如何做到的.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
现在你只需在PHP文件中创建另一个$ _POST ['field1'].