You can call Ajax by clicking on select
and pass id
of select
clicked on the URL to be requested. This way you can control what information will be sent by ASP with request("id")
.
Create a click
event that will detect the select
and send via $.get
o id
of its element. The ASP return (we'll see later) will return objects with two values each, separated by commas, where one value will be value
and the other the text of option
a popular select
clicked. >
In Ajax's return you convert these objects to the JSON array with the JSON.parse()
method, and using $.each
you mount the option
HTML. After $.each
you just have to play the assembled HTML in select
with .html()
.
Further explanation on the codes.
Example of select
with id
:
<select id="cursos"></select>
Event and Ajax code:
$('select').click(function(){ // evento click
// este if verifica se o select já foi populado
// evitando que ele seja populado mais de uma vez
// ao ser clicado
if(!$('option', this).length){
$(this).prop("disabled", true); // desabilita o select
var id = this.id; // pega o id do select
var url_ = 'pagina.asp?id='+id; // monto a URL do Ajax passando o id como parâmetro para o ASP
$.get(url_, function(data){
// aqui é o retorno do Ajax
data = data.replace(/,$/, ''); // removo a última vírgula que virá
data = JSON.parse('[' + data + ']'); // converto os objetos em array JSON
var opts = ''; // declaro a variável que irá montar o HTML das options
$.each(data, function(index, item) {
// monto as options concatenando os valores de cada objeto
opts += '<option value="'+item.id+'">'+item.campo+'</option>';
});
$('#'+id).html(opts) // envio o HTML montado para o devido select
.prop("disabled", false); // habilita o select novamente
});
}
});
Change pagina.asp
to your ASP page.
Mounting objects in ASP and returning to Ajax:
In ASP you get the id
sent by Ajax with request("id")
, and according to the value received, you mount the query to the database.
Normally loop the query to the bank and place the response.write
within that loop by mounting the objects that will be sent to Ajax. Example:
<%
conn = conexão com o banco
set rs = conn.execute(aqui a sua query)
if not rs.eof then
while not rs.eof
response.write("{""id"":"""& rs("coluna_id") &""",""campo"":"""& rs("coluna_campo") &"""},")
rs.movenext
wend
end if
rs.close
set rs = nothing
%>
The ASP page should have only the above code. Not a normal page
with tags.