Mysql
 SQL >> Database >  >> RDS >> Mysql

Popolare una select dal database con jQuery

Questo script costruisce le opzioni dal JSON restituito da una pagina PHP:

$.getJSON("yourPHPPage.php", function (data) {
    $.each(data, function (index, item) {
        $('<option>', {
            value: item.ID,
            text: item.Name
        }).appendTo("#a1_title");
    });
});

La risposta attesa può essere simile a:

[
  { "ID": "1", "Name": "Scott" },
  { "ID": "2", "Name": "Jon" }
]

Evita SELECT * per riempire una dropdown: recupera solo ID e Name.

Note di robustezza

Costruire HTML per concatenazione di stringhe si rompe se un nome contiene virgolette o parentesi angolari. Preferisci metodi DOM, che gestiscono escaping. Aggiungi anche un handler .fail(), così una richiesta fallita mostra un messaggio invece di lasciare la select vuota.