这是一个我认为相当常见的问题(或设计模式?),因此我希望这篇文章可以帮助其他遇到类似问题的人......
我有一个不太常见的情况,需要动态地允许用户编辑依赖于用户做出的其他选择的数据的复杂表单。我正在使用Ajax、jQuery与PHP以及后端数据库postgres。
我已经想出了如何基于用户选择的两个值返回单个记录的数据,使用了jQuery Ajax技术(对于这种情况,Ajax比php更加出色);通常返回值将是一个记录,我的HTML表单可以处理。但有时返回值将是两个或三个记录。在这种情况下,我需要动态添加输入字段并用返回的数据填充它们。
这是我的表单中的代码;Fetch按钮获取所选标记值和所选LabID值来查找相关记录,其中包含Allele_1、Allele_2和Run日期:
<fieldset>
<LEGEND><b>Edit Genotype</b></LEGEND>
<p>
<boldlabel>Selected Marker</boldlabel><input name=sel_marker length=15 DISABLED>
<boldlabel>Selected LabID</boldlabel><input name=sel_labid length=10 DISABLED><br>
<boldlabel>Allele_1</boldlabel><input id=allele1 name=allele_1 size=5 >
<boldlabel>Allele_2</boldlabel><input id=allele2 name=allele_2 size=5 >
<boldlabel>Run date</boldlabel><input id=run_date name=run_date size=10 >
<br>
</p>
<input type="button" name="fetch" id="fetchbutton" value="Fetch" sclass="btn">
<input type="button" name="save" value="Save" onclick="savegenotype()" class="btn">
<br>
</fieldset>
这是与“获取”按钮相关联的JavaScript代码:
function fetchgenotype() {
// here's where we use an Ajax function to fetch the allele values without reloading the page.
// Get the index number of the genotype record to retrieve; retrieve it; populate the alleles.
var mndx = document.EditGenotype.marker.options[document.EditGenotype.marker.selectedIndex].value;
var sndx = document.EditGenotype.labid.options[document.EditGenotype.labid.selectedIndex].value;
$.post("fetchAlleles.php", {mndx: mndx, sndx: sndx},
function(result) {
i=0;
result.each(
a1='allele1_'||i.toString();
a2='allele2_'||i.toString();
r='rundate_'||i.toString();
$("#run_date").after(a1);
$("#run_date").after(a2);
$("#run_date").after(r);
)
}, "json");
return false;
}
这里是单独的 PHP 脚本,即 Ajax 部分,用于查找相关数据:
// query the database.
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'fetchAlleles',16,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT allele1, allele2, run_date FROM geno.genotypes WHERE markers_id=".$mndx." AND gsamples_id=".$sndx;
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$arr = pg_fetch_array($fetchresult, 0, PGSQL_NUM);
// for debugging
//print_r($arr);
} else {
echo "(25) Failed to retrieve results.<BR>SQL: ".$sql."</br>";
}
// It appears necessary to return the array as json encapsulated.
echo json_encode($arr);
?>
}
我知道,对于单一数值情况,这部分代码是有效的;但是当返回值为多条记录的数组时,我的javascript表单中jQuery代码的语法不正确。我在以下这行代码中遇到了错误 a1='allele1_'||i.toString();
希望有jQuery高手能够帮我解决这个问题,非常感谢...