2012-05-02 172 views
3

這是一個問題(或設計模式?),我認爲這是相當普遍的,所以我希望這篇文章可能會幫助其他人有類似的問題....如何在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的大師誰可以把我直接將讚賞...

+0

你還可以發佈JSON輸出(使用Firebug或Chrom開發工具)所以我們可以看到,你的響應有什麼結構。 –

回答

2

我首先想到的:使用pg_affected_rows找出whethaer你有一個或多個記錄。

我的第二個想法:爲什麼不是pg_fetch_object?我認爲你會得到更好(可讀)的json。

我的第三個想法:你應該統一JSON輸出。 很常見的做法是 - JSON響應應該看起來像一個對象數組。如果DB只返回一條記錄 - > JSON-response是一個只有一個條目的數組。如果DB返回多個 - > JSON-響應是JSON-響應

//DB return only ONE record 
    { 
     "items": [ 
      { 
       "allele1" : "the-value", 
       "allele2" : "the-value", 
       "run_date" : "the-date" 
      } 
     ], 
     "totalItems : 1 
    } 

//DB returns more than one records 
{ 
    "items": [ 
     { 
      "allele1" : "the-value_1", 
      "allele2" : "the-value_1", 
      "run_date" : "the-date_1" 
     }, 
     { 
      "allele1" : "the-value_2", 
      "allele2" : "the-value_2", 
      "run_date" : "the-date_2" 
     }, 
     ... 
     { 
      "allele1" : "the-value_n", 
      "allele2" : "the-value_n", 
      "run_date" : "the-date_n" 
     } 
    ], 
    "totalItems : n 
} 

如果你被造成這樣的,你可以更容易創建它的

實例與多個項目的數組INPUT-動態地。所有的 首先,你可以很容易檢查,如果你收到一個或多個記錄

if(response.totalItems === 1) { 
    // handle single record 
}else if (response.totalItems > 1) { 
    // handle multiple records 
} 

中的多個記錄的情況下,你可以遍歷與jQuery.each()& jQuery.map(),併產生inputfields

if (response.totalItems > 0) { 
    //iterate through all items in JSON-response 
    $.each(response.items, function(index, object) { 
     // create FIELDSET element 
     var $fieldset = $('<fieldset>', {'html' : '<legend>#'+(index+1)+'</legend>'}); 

     $.map(object, function(value ,key) { 
      //create LABEL element and appendInto FIELDSET 
      $fieldset.append($('<label>', {'text' : key, 'for' : key})); 
      //create INPUT element and appendInto FIELDSET 
      $fieldset.append($('<input>', {'id': key, 'name': key, 'value' : value})); 
      //create LineBreak 
      $fieldset.append('<br />'); 
     }); 
     // Append whole FIELDSET with LABEL, INPUT and BR to body (or whatever your placeholder is) 
     $('body').append($fieldset); 
    }); 
} 
+0

感謝V-Light!這看起來完全像我所需要的。將嘗試並讓你知道... – rixter

相關問題