Foros del Web » Programando para Internet » Javascript »

Como capturar parámetro get de la URL y meterlo en este código .js

Estas en el tema de Como capturar parámetro get de la URL y meterlo en este código .js en el foro de Javascript en Foros del Web. Hola a tod@s, estoy atascado y ya no se por donde tirar. Os explico un poco de que va el tema: tengo una página que ...
  #1 (permalink)  
Antiguo 15/12/2011, 08:59
Avatar de angel_dope  
Fecha de Ingreso: noviembre-2002
Ubicación: Valencia
Mensajes: 737
Antigüedad: 21 años, 5 meses
Puntos: 8
Como capturar parámetro get de la URL y meterlo en este código .js

Hola a tod@s, estoy atascado y ya no se por donde tirar. Os explico un poco de que va el tema: tengo una página que al pulsar el un botón abre un interstitial que carga otra página. Pues resulta que necesito pasarle de alguna forma un parámetro y no se como hacerlo, ya que por medio hay un archivo .js

Lo que quiero es que este archivo .js lea uno de los parámetros de la url y lo añada en un punto del código. Os adjunto el código y se verá más claro. Digamos que la url es pagina.asp?p1=55&p2=39&c=999 Quiero capturar únicamente el parámetro C. El código del .js es el siguiente (en la linea 9 debería meter el parámetro capturado):

Código Javascript:
Ver original
  1. //Interstitial Content Box v1.1- http://www.dynamicdrive.com/dynamicindex17/interstitial.htm
  2. //Last modified: Nov 26th, 06' (New: disable webpage scrollbar, auto hide after x seconds options,
  3.  
  4. var interstitialBox={
  5. //1) list of files on server to randomly pick from and display
  6.  
  7. ---AQUI NECESITARÍA CAPTURAR LA VARIABLE C DE LA URL Y METERLA EN LA SIGUIENTE LINEA DE FORMA QUE QUEDASE "ftp=2&c=loquesecaptura"---
  8.  
  9. displayfiles: ['samplecontent.asp?ftp=2'],
  10.  
  11. //2) display freqency: ["frequency_type", "frequency_value"]
  12. displayfrequency: ["chance", "1"],
  13.  
  14. //3) HTML for the header bar portion of the interstitial box
  15. defineheader: '<div class="headerbar"><a href="#" onClick="javascript:interstitialBox.closeit(); return false"><img src="closeit.gif" style="border: 0" title="Close Box"/></a></div><table width="100%" border="0"><tr><td><img src="banner.jpg" width="898" height="42" /></td></tr></table>',
  16.  
  17. //4) cookie setting: ["cookie_name", "cookie_path"]
  18. cookiesetting: ["stitialcookie", "path=/"],
  19.  
  20. //5) bust caching of pages fetched via Ajax?
  21. ajaxbustcache: true,
  22.  
  23. //6) Disable browser scrollbars while interstitial is shown (Only applicable in IE7/Firefox/Opera8+. IE6 will just auto scroll page to top)?
  24. disablescrollbars: true,
  25.  
  26. //7) Auto hide Interstitial Box after x seconds (0 for no)?
  27. autohidetimer: 0,
  28.  
  29. ////No need to edit beyond here//////////////////////////////////
  30.  
  31. ie7: window.XMLHttpRequest && document.all && !window.opera,
  32. ie7offline: this.ie7 && window.location.href.indexOf("http")==-1, //check for IE7 and offline
  33. launch:false,
  34. scrollbarwidth: 16,
  35.  
  36. ajaxconnect:function(url, thediv){
  37. var page_request = false
  38. var bustcacheparameter=""
  39. if (window.XMLHttpRequest && !this.ie7offline) // if Mozilla, IE7 online, Safari etc
  40. page_request = new XMLHttpRequest()
  41. else if (window.ActiveXObject){ // if IE6 or below, or IE7 offline (for testing purposes)
  42. try {
  43. page_request = new ActiveXObject("Msxml2.XMLHTTP")
  44. }
  45. catch (e){
  46. try{
  47. page_request = new ActiveXObject("Microsoft.XMLHTTP")
  48. }
  49. catch (e){}
  50. }
  51. }
  52. else
  53. return false
  54. page_request.onreadystatechange=function(){
  55. interstitialBox.loadpage(page_request, thediv)
  56. }
  57. if (this.ajaxbustcache) //if bust caching of external page
  58. bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
  59. page_request.open('GET', url+bustcacheparameter, true)
  60. page_request.send(null)
  61. },
  62.  
  63. loadpage:function(page_request, thediv){
  64. if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
  65. document.getElementById("interContent").innerHTML=page_request.responseText
  66. }
  67. },
  68.  
  69. createcontainer:function(){
  70. //write out entire HTML for Interstitial Box:
  71. document.write('<div id="interContainer">'+this.defineheader+'<div id="interContent"></div></div><div id="interVeil"></div>')
  72. this.interContainer=document.getElementById("interContainer") //reference interstitial container
  73. this.interVeil=document.getElementById("interVeil") //reference veil
  74. this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
  75. },
  76.  
  77.  
  78. showcontainer:function(){
  79. if (this.interContainer.style.display=="none") return //if interstitial box has already closed, just exit (window.onresize event triggers function)
  80. var ie=document.all && !window.opera
  81. var dom=document.getElementById
  82. var scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset
  83. var scroll_left=(ie)? this.standardbody.scrollLeft : window.pageXOffset
  84. var docwidth=(ie)? this.standardbody.clientWidth : window.innerWidth-this.scrollbarwidth
  85. var docheight=(ie)? this.standardbody.clientHeight: window.innerHeight
  86. var docheightcomplete=(this.standardbody.offsetHeight>this.standardbody.scrollHeight)? this.standardbody.offsetHeight : this.standardbody.scrollHeight
  87. var objwidth=this.interContainer.offsetWidth
  88. var objheight=this.interContainer.offsetHeight
  89. this.interVeil.style.width=docwidth+"px" //set up veil over page
  90. this.interVeil.style.height=docheightcomplete+"px" //set up veil over page
  91. this.interVeil.style.left=0 //Position veil over page
  92. this.interVeil.style.top=0 //Position veil over page
  93. this.interVeil.style.visibility="visible" //Show veil over page
  94. this.interContainer.style.left=docwidth/2-objwidth/2+"px" //Position interstitial box
  95. var topposition=(docheight>objheight)? scroll_top+docheight/2-objheight/2+"px" : scroll_top+5+"px" //Position interstitial box
  96. this.interContainer.style.top=Math.floor(parseInt(topposition))+"px"
  97. this.interContainer.style.visibility="visible" //Show interstitial box
  98. if (this.autohidetimer && parseInt(this.autohidetimer)>0 && typeof this.timervar=="undefined")
  99. this.timervar=setTimeout("interstitialBox.closeit()", this.autohidetimer*1000)
  100. },
  101.  
  102.  
  103. closeit:function(){
  104. this.interVeil.style.display="none"
  105. this.interContainer.style.display="none"
  106. if (this.disablescrollbars && window.XMLHttpRequest) //if disablescrollbars enabled and modern browsers- IE7, Firefox, Safari, Opera 8+ etc
  107. this.standardbody.style.overflow="auto"
  108. if (typeof this.timervar!="undefined") clearTimeout(this.timervar)
  109. },
  110.  
  111. getscrollbarwidth:function(){
  112. var scrollbarwidth=window.innerWidth-(this.interVeil.offsetLeft+this.interVeil.offsetWidth) //http://www.howtocreate.co.uk/emails/BrynDyment.html
  113. this.scrollbarwidth=(typeof scrollbarwidth=="number")? scrollbarwidth : this.scrollbarwidth
  114. },
  115.  
  116. hidescrollbar:function(){
  117. if (this.disablescrollbars){ //if disablescrollbars enabled
  118. if (window.XMLHttpRequest) //if modern browsers- IE7, Firefox, Safari, Opera 8+ etc
  119. this.standardbody.style.overflow="hidden"
  120. else //if IE6 and below, just scroll to top of page to ensure interstitial is in focus
  121. window.scrollTo(0,0)
  122. }
  123. },
  124.  
  125. dotask:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
  126. var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
  127. if (target.addEventListener)
  128. target.addEventListener(tasktype, functionref, false)
  129. else if (target.attachEvent)
  130. target.attachEvent(tasktype, functionref)
  131. },
  132.  
  133. initialize:function(){
  134. this.createcontainer() //write out interstitial container
  135. this.ajaxconnect(this.displayfiles[Math.floor(Math.random()*this.displayfiles.length)], this.interContainer) //load page into content via ajax
  136. this.dotask(window, function(){interstitialBox.hidescrollbar(); interstitialBox.getscrollbarwidth(); setTimeout("interstitialBox.showcontainer()", 100)}, "load")
  137. this.dotask(window, function(){interstitialBox.showcontainer()}, "resize")
  138. }
  139. }
  140.  
  141. /////////////End of interstitialBox object declaration here ////////////////////////////////
  142.  
  143. function getCookie(Name){
  144. var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
  145. if (document.cookie.match(re)) //if cookie found
  146. return document.cookie.match(re)[0].split("=")[1] //return its value
  147. return null
  148. }
  149.  
  150. function setCookie(name, value, days){
  151. var expireDate = new Date()
  152. //set "expstring" to either an explicit date (past or future)
  153. if (typeof days!="undefined"){ //if set persistent cookie
  154. var expstring=expireDate.setDate(expireDate.getDate()+parseInt(days))
  155. document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; "+interstitialBox.cookiesetting[1]
  156. }
  157. else //else if this is a session only cookie setting
  158. document.cookie = name+"="+value+"; "+interstitialBox.cookiesetting[1]
  159. }
  160.  
  161.  
  162. var stitialvars=new Object() //temporary object to reference/ shorthand certain interstitialBox properties
  163. stitialvars.freqtype=interstitialBox.displayfrequency[0] //"chance" or "cookie"
  164. stitialvars.cookieduration=interstitialBox.displayfrequency[1] //"session" or int (integer specifying number of days)
  165. stitialvars.cookiename=interstitialBox.cookiesetting[0] //name of cookie to use
  166.  
  167.  
  168. if (stitialvars.freqtype=="chance"){ //IF CHANCE MODE
  169. if (Math.floor(Math.random()*interstitialBox.displayfrequency[1])==0)
  170. interstitialBox.launch=true
  171. }
  172. else if (stitialvars.freqtype=="cookie" && stitialvars.cookieduration=="session"){ //IF "SESSION COOKIE" MODE
  173. if (getCookie(stitialvars.cookiename+"_s")==null){ //if session cookie is empty
  174. setCookie(stitialvars.cookiename+"_s", "loaded")
  175. interstitialBox.launch=true
  176. }
  177. }
  178. else if (stitialvars.freqtype=="cookie" && typeof parseInt(stitialvars.cookieduration)=="number"){ //IF "PERSISTENT COOKIE" MODE
  179. if (getCookie(stitialvars.cookiename)==null || parseInt(getCookie(stitialvars.cookiename))!=parseInt(stitialvars.cookieduration)){ //if persistent cookie is empty or admin has changed number of days to persist from that of the stored value (meaning, reset it)
  180. setCookie(stitialvars.cookiename, stitialvars.cookieduration, stitialvars.cookieduration)
  181. interstitialBox.launch=true
  182. }
  183. }
  184.  
  185. if (interstitialBox.launch)
  186. interstitialBox.initialize()

Hay alguna forma de hacer esto?? Muchas gracias por adelantado, salu2
__________________
Vayamos por Partes :: Jack el Destripador
  #2 (permalink)  
Antiguo 15/12/2011, 09:17
 
Fecha de Ingreso: mayo-2008
Mensajes: 103
Antigüedad: 16 años
Puntos: 14
Respuesta: Como capturar parámetro get de la URL y meterlo en este código .js

No te entiendo demasiado bien...
¿La variable C la tienes en JS o en PHP?
¿No te funciona si se la añades igual que añades a la de FTP?

Código:
displayfiles: ['samplecontent.asp?ftp=2&c=blabla']
Si la variable la tienes en PHP pues la cargas...


Código:
<?php
$c = Blabla;
?>
displayfiles: ['samplecontent.asp?ftp=2&c=<?php echo $c;?>']
  #3 (permalink)  
Antiguo 15/12/2011, 09:25
Avatar de angel_dope  
Fecha de Ingreso: noviembre-2002
Ubicación: Valencia
Mensajes: 737
Antigüedad: 21 años, 5 meses
Puntos: 8
Respuesta: Como capturar parámetro get de la URL y meterlo en este código .js

A ver si lo puedo explicar mejor, que me parece que no lo he hecho muy bien jeje. El código que he puesto es un archivo .js. es decir, javascript. Y lo que no se es como dentro de ese archivo .js hacer la captura del parámetro, porque imagino que si hago un request.querystring (como en asp) no funcionará... o tal vez si, al estar con un include dentro del asp??? Voy a probarlo y ya os cuento
__________________
Vayamos por Partes :: Jack el Destripador
  #4 (permalink)  
Antiguo 15/12/2011, 09:32
Avatar de angel_dope  
Fecha de Ingreso: noviembre-2002
Ubicación: Valencia
Mensajes: 737
Antigüedad: 21 años, 5 meses
Puntos: 8
Respuesta: Como capturar parámetro get de la URL y meterlo en este código .js

Pues no, no funciona... de todas formas, estoy pensando que tampoco me serviría si lo consigo :S así que nada, voy a probar con una solución alternativa que estoy pensando, a ver si funciona!!
__________________
Vayamos por Partes :: Jack el Destripador
  #5 (permalink)  
Antiguo 15/12/2011, 11:35
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: Como capturar parámetro get de la URL y meterlo en este código .js

buenas,
en ese caso tienes que generar el archivo *.js con php. es decir, es un archivo *.js común y corriente, solo que le cambias la extensión a *.php. luego, al inicio del código debes indicar el content-type en que debe servirse dicho archivo, o sea text/javascript. ahora puedes escribir código php dentro tal como lo harias en un html. y finalmente, tienes que corregir la url en el documento html que carga el archivo *.js, que en realidad ahora va ser *.php.
__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.

Etiquetas: ajax, html, js, url
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 00:07.