首先我要说的是,虽然我很擅长 PHP 和 HTML,但我对 javascript/jquery 不太了解。如果之前已经回答过这个问题,我也深表歉意,但我在搜索中没有找到任何东西。
我正在开发一个项目,其中我们有一个大小未定的表单,我想在其中构建一些自动完成功能。表单字段和必要的 div 使用计数器命名,如下面的代码所示。
$set_b = 'upl_band'.$count;
$sugbox = $set_b."sug";
$autobox = $set_b."auto";
echo "<div><input type=text name='$set_b' size=25 id='$set_b' onkeyup='bandlookup(this.value,'$set_b');' onblur='bandfill();'></div>";
echo "<div class='suggestionsBox' id='$sugbox' style='display: none;'><img src='upArrow.png' style='position: relative; top: -12px; left: 30px;' alt='upArrow' /><div class='suggestionList' id='$autobox'> </div></div>";
我正在尝试将主值 - $set_b 传递到我的 javascript onkeyup 中。然而,在这个过程中,我正在失去我的值(value)观。如果我使用具体的 id 设置表单,则此代码可以正常工作,但是当我创建 id 变量时,我会迷路。我的 JavaScript 如下。对 band.php 的 post 调用是我的查找脚本。
function bandlookup(bandString, boxName) {
if(bandString.length == 0) {
// Hide the suggestion box.
var s = boxName+"sug";
$("#"+s).hide();
} else {
var su = boxName+"sug";
var suauto = boxName+"auto";
$.post("band.php", {queryString: ""+bandString+"", inputName: ""+boxName+""}, function(data){
if(data.length >0) {
$("#"+su).show();
$("#"+suauto).html(data);
}
});
}
} // lookup
function bandfill(thisValue, boxName) {
var s = boxName+"sug";
$("#"+boxName).val(thisValue);
setTimeout("$('#'+s).hide();", 200);
}
和 band.php
$db = new mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$box = $_POST['inputName'];
// Is the string length greater than 0?
if(strlen($queryString) >0) {
$query = $db->query("SELECT band_name,band_id FROM upl_band WHERE band_name LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
echo '<li onClick="bandfill(\''.$result->band_name.'\',\''.$box.'\');">'.$result->band_name.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
我的问题可能出在 javascript 中的 post 调用,但我更倾向于我不正确地将变量变量名作为 id 标签处理。
最佳答案
你的绳子断了,试试这个:
echo "<div><input type=text name='$set_b' size=25 id='$set_b' onkeyup=\"bandlookup(this.value,'$set_b');\" onblur='bandfill();'></div>";
关于php - 在 javascript 和 php 之间来回传递表单 ID 作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6065616/