Foros del Web » Programando para Internet » ASP Clásico »

Ajax con ASP

Estas en el tema de Ajax con ASP en el foro de ASP Clásico en Foros del Web. Cita: Iniciado por darkmcloud pero aunque quite esa linea no me rellena el segundo campo..... mi idea es que cuando yo voy escribiendo me va ...

  #31 (permalink)  
Antiguo 04/01/2010, 15:06
Avatar de Adler
Colaborador
 
Fecha de Ingreso: diciembre-2006
Mensajes: 4.671
Antigüedad: 18 años, 3 meses
Puntos: 126
Respuesta: Ajax con ASP

Cita:
Iniciado por darkmcloud Ver Mensaje
pero aunque quite esa linea no me rellena el segundo campo.....
mi idea es que cuando yo voy escribiendo me va dando las sugerencias cierto?
entonces me gustaría que cuando elija una de las sugerencias me rellene automáticamente el campo de familia.....pero con las modificaciones no pasa nada....

De antemano muchas gracias (por toda la colaboracion y tu paciencia Adler)

Todo lo hecho desde el post #22 no vale para nada. Veamos si es esto lo que buscas

Todos los cambios ha de hacerlo únicamente en SelectUsuariosAjax.asp. No has de toca SelecUsuarios.asp

Cita:
<script type="text/javascript">
var familia = "";
var SelUsuario = {
Cita:
Despliega: function () {
var obj = document.getElementById("contenedor");
if (ajax.readyState==1 || ajax.readyState==2 || ajax.readyState==3) {
obj.innerHTML = "<p align='center'><img src='../images/cargando.gif' border='0px' widht='15px' height='15px'/></p>";
obj.style.display= "block";
}
else if (ajax.readyState==4) {
if (ajax.status==200) {
var division = unescape(ajax.responseText);
obj.innerHTML = division.split("-")[0];
familia = division.split("-")[1];
}else {
Cita:
Seleccionar: function () {
var ref = document.getElementById(this.id).getElementsByTagN ame('DIV');
//alert(ref);for (var i = 0; i < ref.length; i++) {
SelUsuario.Evento(ref[i], 'click', function() {
SelUsuario.Pegar(this.id, familia);
Cita:
Pegar: function (valor, f) {
//alert("el val " +valor);
var obj = document.getElementById("contenedor")
document.getElementById("txt").value = valor;
document.getElementById("fam").value = f;
if (obj.style.display == "block"); obj.style.display= "none";
},
Suerte
__________________
Los formularios se envían/validan con un botón Submit
<input type="submit" value="Enviar" style="background-color:#0B5795; font:bold 10px verdana; color:#FFF;" />
  #32 (permalink)  
Antiguo 04/01/2010, 15:25
 
Fecha de Ingreso: octubre-2007
Mensajes: 191
Antigüedad: 17 años, 6 meses
Puntos: 0
Respuesta: Ajax con ASP

puxila!! creo q vamos cerca......pero el problema es que en familia se rellena con valores asi:

Cita:
2066" class="">MOTOR HT
o sea si se acerca al valor de "familia"

Asi quedo ahora:

SelectUsuariosAjax.asp

Código ASP:
Ver original
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html xmlns="http://www.w3.org/1999/xhtml"lang="es" xml:lang="es">
  3. <head>
  4. <meta name="http-equiv" content="Content-type: text/html; charset=UTF-8"/>
  5. <STYLE TYPE="text/css">
  6. #contenedor div.seleccionado {font-weight:bold; background:#F0F0F0; color:#black;}
  7. #contenedor div.deseleccionado {background:#FFFFFF; color:#000000;}
  8. #contenedor div{font:11px verdana; color:#000000; cursor:pointer; text-align:left; padding:2px 5px;}
  9.  
  10. .capa {
  11. background: #FFFFFF;
  12. border:1px solid rgb(120,120,120);
  13. width: 150px;
  14. _width: 250px;
  15. text-align: left;
  16. position: absolute;
  17. top: 30px;
  18. _top:38px;
  19. left: 117px;
  20. _left: 119px;
  21. }
  22. </STYLE>
  23. <script type="text/javascript">
  24. var familia = "";
  25. var SelUsuario = {
  26.  
  27. Evento: function (elemento,nomevento,funcion) {
  28.   if (elemento.attachEvent)
  29.   {
  30.       var f=function(){
  31.         funcion.call(elemento,window.event);
  32.     }
  33.     elemento.attachEvent('on'+nomevento,f);
  34.     return true;
  35.   }
  36.   else  
  37.     if (elemento.addEventListener)
  38.     {
  39.       elemento.addEventListener(nomevento,funcion,false);
  40.       return true;
  41.     }
  42.     else
  43.       return false;
  44. },
  45.  
  46. init: function(){
  47. var elem1 = document.getElementById("txt");
  48. var elem2 = document.getElementById("contenedor");
  49.         SelUsuario.Evento(elem1, 'keyup', SelUsuario.Empieza);
  50.         SelUsuario.Evento(elem2, 'mouseover', SelUsuario.Seleccionar);
  51.         SelUsuario.Evento(elem1, 'keydown', SelUsuario.Pegar2);
  52.         SelUsuario.Evento(window, 'click', SelUsuario.Cerrar);
  53.     },
  54.  
  55. creaAjax: function (){
  56.     var ajaxs = ["Msxml2.XMLHTTP","Msxml2.XMLHTTP.4.0","Msxml2.XMLH TTP.5.0","Msxml2.XMLHTTP.3.0","Microsoft.XMLHTTP"];
  57.     var ajax = false;
  58.     for(var i=0 ; !ajax && i<ajaxs.length ; i++){
  59.         try{
  60.             ajax = new ActiveXObject(ajaxs[i]);   // Internet Explorer
  61.         }
  62.         catch(e) {
  63.             ajax = false;
  64.         }
  65.     }
  66.     if(!ajax && typeof XMLHttpRequest!='undefined') {
  67.         ajax = new XMLHttpRequest();  // Firefox, Opera 8.0+, Safari
  68.     }
  69.     return ajax;
  70. },
  71.  
  72. Empieza: function (ev) {
  73. var str = document.getElementById(this.id).value;
  74. var obj = document.getElementById("contenedor");
  75. var obj2 = document.getElementById("stock").options[document.getElementById("stock").selectedIndex].value;
  76. var ref = obj.getElementsByTagName('DIV');
  77. var keyCode = document.layers ? ev.which : document.all ? event.keyCode : document.getElementById ? ev.keyCode : 0;
  78.  
  79.  if (keyCode == 40) {
  80. //alert("flecha abajo")
  81.     SelUsuario.BajaOpt ()
  82.  } else if (keyCode == 38) {
  83. //alert("flecha arriba")
  84.     SelUsuario.SubeOpt ()
  85.  
  86. } else if (keyCode == 13) {
  87.  
  88. for (var i = 0; i <= ref.length-1; i++) {
  89. if (ref[i].className == "seleccionado") {
  90.  
  91.         document.getElementById("txt").value = ref[i].id;
  92.         if (obj.style.display == "block"); obj.style.display= "none";
  93.         break;
  94.         }
  95.  
  96.     }
  97.  
  98.     try{ // DOM;
  99.         ev.preventDefault();
  100.         }catch(e){ // iexplore;
  101.         ev.returnValue = false;
  102.         }
  103.  
  104. } else {
  105.  
  106.     if (str.length < 2) {
  107.         //obj.innerHTML = "";
  108.         if (obj.style.display == "none")  obj.style.display= "none";
  109.                 else obj.style.display= "none";
  110.         return;
  111.     }
  112.     ajax = SelUsuario.creaAjax()
  113.     if (ajax==null) {
  114.         alert ("Tu navegador no soporta Ajax");
  115.         return;
  116.      }
  117. var url="SelecUsuarios.asp?q="+escape(str) + "&variable=" +escape(obj2);
  118. //var url="SelecUsuarios.asp?variable=" +obj2 + "&q=" +escape(str);
  119.  
  120.     ajax.open("GET",url,true);
  121.     ajax.onreadystatechange = SelUsuario.Despliega;
  122.     //ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  123.             ajax.send(null);
  124.             return
  125. }
  126. },
  127.  
  128. Despliega: function () {
  129. var obj = document.getElementById("contenedor");
  130.    
  131. if (ajax.readyState==1 || ajax.readyState==2 || ajax.readyState==3) {
  132. obj.innerHTML = "<p align='center'><img src='../images/cargando.gif' border='0px' widht='15px' height='15px'/></p>";
  133.             obj.style.display= "block";
  134.                 }
  135.  
  136.                 else if (ajax.readyState==4) {
  137.             if (ajax.status==200) {
  138.            
  139. var division = unescape(ajax.responseText);
  140. obj.innerHTML = division.split("-")[0];
  141. familia = division.split("-")[1];
  142.            
  143.            
  144.             obj.innerHTML = unescape(ajax.responseText);
  145.  
  146.             }else {
  147.              obj.innerHTML = "<p>Se ha producido un error</p>";
  148.             }
  149.  
  150.         if (obj.style.display == "none")  obj.style.display= "block";
  151.         }
  152. },
  153.  
  154. Seleccionar: function () {
  155. var ref = document.getElementById(this.id).getElementsByTagName('DIV');
  156. //alert(ref);
  157. for (var i = 0; i < ref.length; i++) {
  158.  
  159. SelUsuario.Evento(ref[i], 'click', function() {
  160. SelUsuario.Pegar(this.id, familia);
  161. //alert(this.id);
  162. })  
  163.  
  164. SelUsuario.Evento(ref[i], 'mouseover',  function() {
  165. SelUsuario.Marcar(this.id);
  166. })
  167.  
  168. //SelUsuario.Evento(ref[i], 'mouseout',  function() {
  169. //SelUsuario.DesMarcar(this.id);
  170. //})
  171. }
  172. },
  173.  
  174.  
  175. Pegar: function (valor, f) {
  176. //alert("el val " +valor);
  177. var obj = document.getElementById("contenedor")
  178. document.getElementById("txt").value = valor;
  179. document.getElementById("fam").value = f;
  180.                 if (obj.style.display == "block"); obj.style.display= "none";      
  181. },
  182.  
  183. Pegar2: function (ev) {
  184. var obj = document.getElementById("contenedor")
  185. var ref = obj.getElementsByTagName('DIV');
  186. var keyCode = document.layers ? ev.which : document.all ? event.keyCode : document.getElementById ? ev.keyCode : 0;
  187.  
  188. // enter 13 tab 9
  189. if ((keyCode == 13) || (keyCode == 9)) {
  190. //alert("enter")
  191.  
  192. for (var i = 0; i <= ref.length-1; i++) {
  193. if (ref[i].className == "seleccionado") {
  194.  
  195.         document.getElementById("txt").value = ref[i].id;
  196.         //window.focus();
  197.         if (obj.style.display == "block"); obj.style.display= "none";
  198. break;
  199. //alert(ref[i].id);
  200.  
  201.  
  202. }
  203. }
  204.  
  205. if (keyCode == 13) {
  206.     try{ // DOM;
  207.         ev.preventDefault();
  208.         }catch(e){ // iexplore;
  209.         ev.returnValue = false;
  210.         }
  211. }
  212.  
  213.  
  214. }  
  215. },
  216.  
  217.  
  218.  
  219.  
  220.  
  221. BajaOpt: function() {
  222. var ref = document.getElementById("contenedor").getElementsByTagName('DIV');
  223. for (var i = 0; i <= ref.length-1; i++) {
  224. if (ref[i].className == "seleccionado") {
  225. ref[i].className = "deseleccionado";
  226. if (i < ref.length-1){
  227. i++;
  228. }else{
  229. i = 0;
  230. }
  231. //alert("Largo: " +(ref.length-1)+ " Valor: " +i);
  232. ref[i].className = "seleccionado"
  233. }
  234. }
  235. },
  236.  
  237.  
  238. SubeOpt: function() {
  239. var ref = document.getElementById("contenedor").getElementsByTagName('DIV');
  240. for (var i = 0; i <= ref.length-1; i++) {
  241. if (ref[i].className == "seleccionado") {
  242. ref[i].className = "deseleccionado";
  243. if (i < ref.length && i > 0){
  244. i--;
  245. }else{
  246. i = ref.length-1;
  247. }
  248. //alert("Largo: " +(ref.length-1)+ " Valor: " +i);
  249. ref[i].className = "seleccionado"
  250. }
  251. }
  252. },
  253.  
  254. Marcar: function (id) {
  255. var selecionado = document.getElementById(id);
  256. var ref = document.getElementById("contenedor").getElementsByTagName('DIV');
  257. for (var i = 0; i <= ref.length-1; i++) {
  258. if (ref[i].id != id) {
  259. ref[i].className = "deseleccionado";
  260. selecionado.className = "seleccionado";
  261. }
  262. }
  263. },
  264.  
  265. //DesMarcar: function (id) {
  266. //var ref = document.getElementById(id);
  267. //alert(ref);
  268. //ref.className = "deseleccionado"
  269. //alert("el " +id);        
  270. //},
  271.  
  272.  
  273. Cerrar: function () {  
  274. var obj = document.getElementById("contenedor")
  275.             if (obj.style.display == "block"); obj.style.display= "none";  
  276.    
  277. }
  278. }
  279.  
  280. SelUsuario.Evento(window, 'load', SelUsuario.init);
  281. </script>
  282. </head>
  283. <body>
  284. <form method="post" action="">
  285. Nombre Usuario: <input name="txt" type="text" id="txt" tabindex="1" value="" size="40" autocomplete="off" />
  286. <div class="vink" style="margin:5px 0px 0px 10px">
  287. <div id="contenedor" class="capa" style="display:none;"></div></div>
  288. Filtrar: <select id="stock" name="stock">
  289. <option value="constock" selected>Solo con Stock</option>
  290. <option value="sinstock">Sin Stock</option>
  291. </select><br>
  292. <div class="vink" style="margin:5px 0px 0px 10px">
  293. <div id="campo" class="capa" style="display:none;"></div></div>
  294. Familia: <input type="text" name="fam" id="fam" /><br />
  295. <input type="submit" value="Enviar">
  296. </form>
  297. </body>
  298. </html>

Continua......
  #33 (permalink)  
Antiguo 04/01/2010, 15:27
 
Fecha de Ingreso: octubre-2007
Mensajes: 191
Antigüedad: 17 años, 6 meses
Puntos: 0
Respuesta: Ajax con ASP

SelecUsuarios.asp

Código ASP:
Ver original
  1. <%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
  2. <%' Option Explicit %>
  3. <% Response.Buffer=True %>
  4. <% On Error Resume Next  %>
  5. <%Response.charset="utf-8"%>
  6. <%
  7. Response.addHeader "pragma", "no-cache"
  8. Response.CacheControl = "Private"
  9. Response.Expires = -1000
  10. %>
  11. <%
  12. Dim SQL, rs, oConn, registros, i
  13. Dim usuario
  14. Dim nombre
  15. nombre = 0
  16. Dim familia
  17. familia = ""
  18.  
  19. usuario = CStr(Request.QueryString("q"))
  20. combox = CStr(Request.QueryString("variable"))
  21.  
  22. IF Len(usuario) >= 2 then
  23. set Cnn = Server.CreateObject("ADODB.Connection")
  24. set rs = Server.CreateObject ("ADODB.Recordset")
  25. Cnn.Open Session("cnx")
  26.  
  27. SQL="select descrip, familia from producto inner join familias on codi_fami = codi_familia "
  28.  
  29.     se_encuentra = False
  30.        
  31.      if combox = "constock" then
  32.             if se_encuentra then
  33.             SQL=SQL & " AND stock > 0"
  34.                 else
  35.             SQL=SQL & "WHERE stock > 0"
  36.             se_encuentra=True
  37.                   end if
  38.                 end if
  39.                    
  40.         if combox = "sinstock" then
  41.             if se_encuentra then
  42.             SQL=SQL & " AND stock = 0"
  43.                 else
  44.             SQL=SQL & "WHERE  stock = 0"
  45.           se_encuentra=True
  46.                   end if
  47.                     end if
  48.                    
  49.             if usuario <> "" then
  50.               if se_encuentra then
  51.     SQL=SQL & " AND descrip LIKE '"&usuario&"%'"
  52.         else
  53.         SQL=SQL & " WHERE descrip LIKE '"&usuario&"%'"
  54.           se_encuentra=True
  55.                      end if
  56.             end if
  57.  
  58. set rs = Cnn.Execute(SQL)
  59.         If not rs.eof then
  60.         registros = rs.getrows()
  61.         familia = rs.Fields("familia")
  62.             Else
  63.             Response.Write "<p class=""deseleccionado""><strong>Sin resultados</strong></p>"
  64.             Response.End ()
  65.         End If
  66.     rs.Close
  67.     set rs = nothing
  68.     Cnn.Close
  69.     set Cnn = nothing
  70. END IF
  71.  
  72. For i = 0 to Ubound(registros,2)
  73. If i = 0 then
  74. Response.Write "<div id="""& registros(nombre,i) &""" class=""seleccionado"">"& ResaltarSubStr(registros(nombre,i)) & "</div>"
  75. Else
  76. Response.Write "<div id="""& registros(nombre,i) &""" class="""">" & ResaltarSubStr(registros(nombre,i)) & "</div>"
  77. End If
  78. Next
  79.  
  80. ' ========= Funciones ===========
  81. Function ResaltarSubStr(texto)
  82. Dim objRegExp
  83.  
  84.     Set objRegExp= New RegExp
  85. objRegExp.IgnoreCase = True
  86. 'objRegExp.Global = True
  87.  
  88. objRegExp.Pattern = "\b("&usuario&")+(\w)"
  89. texto = objRegExp.Replace(texto, "<strong>$1</strong>$2")
  90.  
  91.     Set objRegExp = Nothing
  92.  
  93.     ResaltarSubStr = texto
  94.  
  95. End Function
  96. ' ========= Fin Funciones ===========
  97. %>

Tuve que hacerlo en 2 post puesto que el foro reclamaba por texto muy largo...jejejee

Aps... cambie un poco la consulta en SelecUsuarios.asp...pero funciona bien solo es para hacer una consulta de más campos a futuro...jejejeje

Esop.... nuevamente graxxx
  #34 (permalink)  
Antiguo 04/01/2010, 15:50
Avatar de Adler
Colaborador
 
Fecha de Ingreso: diciembre-2006
Mensajes: 4.671
Antigüedad: 18 años, 3 meses
Puntos: 126
Respuesta: Ajax con ASP

Hola

Eso ya es un problema en el ASP. Por cierto no veo donde está la repuesta de familia

Response.Write "-" & familia

Suerte
__________________
Los formularios se envían/validan con un botón Submit
<input type="submit" value="Enviar" style="background-color:#0B5795; font:bold 10px verdana; color:#FFF;" />
  #35 (permalink)  
Antiguo 05/01/2010, 06:42
 
Fecha de Ingreso: octubre-2007
Mensajes: 191
Antigüedad: 17 años, 6 meses
Puntos: 0
Respuesta: Ajax con ASP

jajajaja creo que fue un error de post en el foro puesto que si había incluído el response.write familia, pero aún así no me funciona rellenar el campo.....

Hasta pronto y graxxxx
  #36 (permalink)  
Antiguo 11/02/2010, 11:25
 
Fecha de Ingreso: octubre-2007
Mensajes: 191
Antigüedad: 17 años, 6 meses
Puntos: 0
Respuesta: Ajax con ASP

Crees Adler que me podrias ayudar a terminarlo ??
puesto que he intentado de todo y aun no logro que al elegir el campo me rellene el campo de familia.

De antemano muchas gracias
  #37 (permalink)  
Antiguo 11/02/2010, 13:41
Avatar de Adler
Colaborador
 
Fecha de Ingreso: diciembre-2006
Mensajes: 4.671
Antigüedad: 18 años, 3 meses
Puntos: 126
Respuesta: Ajax con ASP

Hola

Cita:
Iniciado por darkmcloud Ver Mensaje
Crees Adler que me podrias ayudar a terminarlo ??
puesto que he intentado de todo y aun no logro que al elegir el campo me rellene el campo de familia.

De antemano muchas gracias
He estado revisando todo el tema por encima y no veo en que más puedo ayudarte. Tienes todo lo necesario para que funcione. Quizás si alguien lo revisase, vería algo que yo no veo

Suerte
__________________
Los formularios se envían/validan con un botón Submit
<input type="submit" value="Enviar" style="background-color:#0B5795; font:bold 10px verdana; color:#FFF;" />
  #38 (permalink)  
Antiguo 12/02/2010, 11:54
 
Fecha de Ingreso: octubre-2007
Mensajes: 191
Antigüedad: 17 años, 6 meses
Puntos: 0
Respuesta: Ajax con ASP

Mi idea básicamente es que por ejemplo escriba en un campo de texto el nombre de una persona, me sugiera las coincidencias y no se , que despliegue el nombre y el apellido de la persona seleccionada me entienden??
El problema es que por más que busco alternativas o algún ejemplo que haga eso pero lamentablemente no lo encuentro :(
Espero que alguien me pueda ayudar.........
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 22:38.