這是一個問題(或設計模式?),我認爲這是相當普遍的,所以我希望這篇文章可能會幫助其他人有類似的問題....如何在jQuery中動態創建和填充文本字段?
我有一個不尋常的情況,需要動態地允許用戶編輯依賴於用戶所做其他選擇的數據。我使用Ajax,jQuery與PHP和postgres作爲後端數據庫。
我已經想出瞭如何基於用戶選擇的兩個值,使用jQuery Ajax技術(Ajax比這個更容易滑動)來返回單個記錄的數據;通常返回值將是一個記錄,這是我的HTML表單可以處理的。但有時候返回值會是兩三條記錄。在這種情況下,我需要動態添加輸入字段並使用返回的數據填充它們。
這是我的表單中的代碼;在取按鈕將選定的標記值和所選拉比德值來查找相關的記錄,它包含Allele_1,Allele_2並運行日期:
<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腳本,該腳本中查找相關數據阿賈克斯部分:
// 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的大師誰可以把我直接將多讚賞...
你還可以發佈JSON輸出(使用Firebug或Chrom開發工具)所以我們可以看到,你的響應有什麼結構。 –