2013-06-29 7 views
11

Sto cercando di fare un html selezionare elenco di aggiornamento opzioni in base a una selezione effettuata su un oggetto di selezione preventiva html. La mia jquery è sotto. Questo viene chiamato correttamente.lista Aggiornamento delle <select> opzioni utilizzando jquery e ajax

var brandName = $("#Brand").val(); 

$.get("updateTypes.php?q="+brandName, function(data) { 

    $("#Type").remove(); 
    var typeData = JSON.parse(data); 

    for (loop=0; loop < typeData.length; ++loop) { 
     $("#Type").options.add(new Option(typeData[loop])); 
    } 
}); 

Come sto usando un Singleton per interfacciarsi con il mio database mySQL, questa funzione jquery chiama un 'intermediario' di file .php chiamato updateTypes.php che è in basso:

include 'databaseInterface.php'; 
$brand = $_GET["q"]; 
$typesData = databaseInterface::getBrandTypes($brand); 
return $typesData; 

Ciò richiede la funzione getBrandTypes nel mio Singleton di seguito:

$query = "SELECT psTypeName FROM types WHERE brands_psBrandName='$BrandName'"; 
$result = mysqli_query($con, $query) or die ("Couldn't execute query. ".mysqli_error($con)); 
$resultArray = array(); 
while ($row = mysqli_fetch_assoc($result)) { 
    extract($row); 
    $resultArray[] = $psTypeName; 
} 

return json_encode($resultArray); 

la pagina web di rimuovere correttamente le opzioni esistenti dalla funzione jquery ma non riesce a aggiornarli. Sembra andare male quando ho decodificare i dati JSON in jQuery. Perché sta andando storto? Il ciclo per l'aggiornamento dell'oggetto selezionato è appropriato?

risposta

16

È possibile utilizzare $.getJSON se vi aspettate una risposta JSON. Si potrebbe anche essere in grado di utilizzare $.each() e poi semplicemente .append() al tag select. È possibile fare riferimento this.property all'interno del .each().

Qualcosa di simile a quanto segue:

$.getJSON("updateTypes.php?q="+brandName, function(data) { 
    $("#Type").remove(); 
    $.each(data, function(){ 
     $("#Type").append('<option value="'+ this.value +'">'+ this.name +'</option>') 
    ) 
}) 

Questo avrebbe assunto la risposta JSON è qualcosa di simile al seguente:

[ { name : "foo", value : "bar" }, { name : "another", value : "example" } ]

+0

Questa risposta è grande, ma come affermato da un altro risposta, l'istruzione '$ ("# Type") rimuovere();.' rimuoverà l'oggetto di selezione. Il modo corretto per farlo è usare '$ (" # Type "). Html ('');'. Manca anche la punteggiatura nel codice della risposta. L'ho risolto –

12

Il codice $("#Type").remove(); rimuove il prescelto non oggetto le sue opzioni. Il modo corretto di rimozione delle opzioni è:

$("#Type option").remove(); 

o

$("#Type").html(''); 

La seconda soluzione sembra essere migliore, come indicato qui: How to remove options from select element without memory leak?

C'è anche un errore nella parte che aggiunge nuove opzioni. Il codice JavaScript dovrebbe essere:

var brandName = $("#Brand").val(); 

$.get("updateTypes.php?q="+brandName, function(data) { 

    $("#Type option").remove(); 
    var typeData = JSON.parse(data); 

    for (loop=0; loop < typeData.length; loop++) { 
     $("#Type").get(0).options.add(new Option(typeData[loop])); 
    } 
}); 

Il metodo $('#Type').get(0) si riferisce all'oggetto DOM grezzo che ha la proprietà "opzioni" che si voleva utilizzare (How to get a DOM Element from a JQuery Selector)