jquery根据另一个输入值自动完成sql查询列表


jquery autocomplete sql query list based on another input value

我的表单中有两个自动完成字段。我使用以下代码填充第一个字段的列表。。。

$result = mysql_query("SELECT * FROM exercise_strength"); 
$arr_autoCompleteExerciseStr=array();
$s=0;
while($row = mysql_fetch_array($result)){
$autoCompleteExerciseStr = "'"".ucfirst($row['exercise'])."'", ";
$arr_autoCompleteExerciseStr[$s] = $autoCompleteExerciseStr;
$s++;
}

而且。。。

$(function() {
    var availableTags = [
        <?php for($k=0; $k<sizeof($arr_autoCompleteExerciseStr); $k++) {echo $arr_autoCompleteExerciseStr[$k]; } ?>
    ];
    $( "#inputExercise" ).autocomplete({
        source: availableTags,
        minLength: 0
    });
    $( "#inputExercise" ).focus(function(){           
        $(this).autocomplete("search");
    });
});

具有不同mysql_query的相同代码用于另一个字段。我想做的是根据第一个字段中键入的内容更改第二个字段的列表。例如,如果用户在第一个字段中键入"胸部",则在第二个字段中显示相关练习的列表,该列表是从我的sql数据库中选择的。

最好的方法是什么?

我更希望我不必离开页面,因为用户必须重新填写表单的其余部分。

请帮忙!:)

--更新--

根据您对JSON的建议,我的代码现在是这样的。

脚本:

$(document).ready(function(){  
  $.post('json_exercise.php', { /**/ }, showExercise, "text");  
});
function showExercise(res){
    var list = JSON.parse(res);
    $("#inputExercise").autocomplete({
        source: list,
        minLength: 0
    });
    $( "#inputExercise" ).focus(function(){           
        $(this).autocomplete("search");
    });
}

PHP文件:

$con = mysql_connect(***);
if (!$con) {die('Could not connect: ' . mysql_error());}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM exercise_strength");
$i = 0;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
  {
      //add the row to the $chat array at specific index of $i
      $exercise[$i] = $row['exercise'];
      $i += 1;
  }
echo json_encode($exercise);

现在我只需要根据第一个自动完成字段中选择的内容来更改php文件。

如果您想在不离开页面的情况下根据SQL查询的结果自动完成,您可能需要研究AJAX和JSON。

此外,请使用PDO而不是mysql_*函数来与带有PHP的DBMS进行接口。