我有一个搜索表单:
<form action="search.php" method="post" name="form" id="form" onsubmit="return false;">
<input name="search" type="text" id="search">
<input name="name" type="text" id="name">
<select name="car" id="car">
<option value="audi">AUDI</option>
<option value=bmw">BMW</option>
<option value="mini">MINI</option>
</select>
<select name="year" id="year">
<option value="2000">2000</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
</select>
</form>
和search.php
<?php
$search = $_POST['search'];
$search = addslashes($search);
$search = htmlspecialchars($search);
$search = stripslashes($search);
$year = $_POST['option'];
$year = addslashes($year);
$year = htmlspecialchars($year);
$year = stripslashes($year);
if($search == '')
exit("Enter name");
elseif(!preg_match("/^[a-zа-я0-9]+$/ui", $search))
exit("Incorrectly");
include 'dbsetting.php';
$mysqli->set_charset("utf8");
$query = "SELECT * FROM cars WHERE (type LIKE '%".$search."%' OR name LIKE '%".$search."%' OR class LIKE '%".$search."%') AND year = '".$year."'";
实时搜索有效。使用AJAX代码:
$(function() {
$("#search").keyup(function(){
var search = $("#search").val();
$.ajax({
type: "POST",
url: "search.php",
data: {"search": search},
cache: false,
success: function(response){
$("#res").html(response);
}
});
return false;
});
});
输入名称=“搜索”正常工作,但我无法添加搜索其他选择和更多输入。如何在ajax代码中添加一些输入并选择以及如何在search.php中保存并添加到搜索结果中?
对不起我的英语。
答案 0 :(得分:2)
您可以将字段发布为名称值对格式,如: -
var search = $("#search").val();
var name = $("#name").val();
var car = $("#car").val();
var year = $("#year").val();
用户在将ajax请求作为数据字段发送时查询字符串。
data: {"search": search, "name":name, "car": car, "year":year},
或者你可以使用$(“form”)。serialize();将所有表单字段自动转换为名称值对,如。
var my_data = $( "form" ).serialize();
// user that variable in your ajax call.
data: my_data,
答案 1 :(得分:1)
试试这个,使用jquery bind
$('#search, #car, #year').bind( "keyup change", function() {
//put your ajax here
});
答案 2 :(得分:0)
$(function() {
$("#search").keyup(function(){
var search = $("#search").val();
var name = $("#name").val();
var car = $("#car").val();
var year = $("#year").val();
$.ajax({
type: "POST",
url: "search.php",
data: {"search": search, "name":name, "car": car, "year":year},
cache: false,
success: function(response){
$("#res").html(response);
}
});
return false;
});
});
答案 3 :(得分:-1)
$(function() {
$("#search").on('keyup',function(){
var search = $("#search").val();
$.ajax({
type: "POST",
url: "search.php",
data: {"search": search},
cache: false,
success: function(response){
$("#res").html(response);
}
});
return false;
});
});