Foros del Web » Programando para Internet » Javascript »

Navegación mediante AJAX

Estas en el tema de Navegación mediante AJAX en el foro de Javascript en Foros del Web. Hola a todos y muy buenas noches Forer@s. Espero puedan ayudarme. Tengo ya buen tiempo sin saber que hacer, dándole vueltas al asunto y sin ...
  #1 (permalink)  
Antiguo 11/05/2018, 22:52
 
Fecha de Ingreso: julio-2015
Ubicación: Distrito Federal
Mensajes: 97
Antigüedad: 8 años, 9 meses
Puntos: 2
Navegación mediante AJAX

Hola a todos y muy buenas noches Forer@s. Espero puedan ayudarme.
Tengo ya buen tiempo sin saber que hacer, dándole vueltas al asunto y sin encontrar alguna solución, la cuestión es que como comento en el título, tengo una navegación mediante AJAX que encontré por allí, y funciona muy bien.
Mi problema viene que cuando cargo la página que tiene un slider de materialize iniciado en un archivo JS que se junto con el otro contenido del AJAX, me explico: Tengo una serie de páginas, en una de ellas hay un carousel o sider que se inicializa con la funcion $('.carousel').carousel({parámetros}); todo el contenido html que especifiqué en la página se muestra bien, pero la función no se ejecuta y por tanto no me muestra el carousel, les adjunto unas imágenes para que me logren entender.

Cuando se carga accediendo directamente a la url en el navegador:



Y aquí cuando se carga la página mediante AJAX:


Cabe destacar que tengo un div principal con una id wrapper, donde se carga todo el contenido, excluyendo el footer, las cabeceras y el menú de navegación. Les dejo un ejemplo del código:
Código PHP:
Ver original
  1. <?php
  2.     $page_title = "Inicio";
  3.     $as_json = false;
  4.    
  5.     if(isset($_GET["view_as"]) && $_GET["view_as"] == "json"){
  6.         $as_json = true;
  7.         ob_start();
  8.     } else {
  9.         include('static/common/topsite.php');
  10.     ?>
  11.     <div id="wrapper">
  12. <?php } ?>
  13.     <div class="container">
  14.         <div class="overlay"><img src="cdn/img/logo.png" alt="Agentes del Infinito"></div>
  15.     </div>
  16.     <!-- MaterializeCSS -->
  17.     <script src="cdn/js/jquery-3.3.1.min.js"></script>
  18.     <script src="cdn/js/materialize.min.js"></script>
  19.     <script src="cdn/js/navigation.js"></script>
  20.     <script src="cdn/js/init.js"></script>
  21. <?php if($as_json){
  22.     echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
  23. } else { ?>
  24.     </div>
  25. <?php include('static/common/footer.php'); } ?>

También les voy a dejar el código para la navegación en ajax, quizá el error está ahí.
Código Javascript:
Ver original
  1. "use strict";
  2. var ajaxRequest = new (function () {
  3.     function closeReq () {
  4.         oLoadingBox.parentNode && document.body.removeChild(oLoadingBox);
  5.         bIsLoading = false;
  6.     }
  7.     function abortReq () {
  8.         if (!bIsLoading) { return; }
  9.         oReq.abort();
  10.         closeReq();
  11.     }
  12.     function ajaxError () {
  13.         alert("Unknown error.");
  14.     }
  15.     function ajaxLoad () {
  16.         var vMsg, nStatus = this.status;
  17.         switch (nStatus) {
  18.             case 200:
  19.                 vMsg = JSON.parse(this.responseText);
  20.                 document.title = oPageInfo.title = vMsg.page;
  21.                 document.getElementById(sTargetId).innerHTML = vMsg.content;
  22.                 if (bUpdateURL) {
  23.                     history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url);
  24.                     bUpdateURL = false;
  25.                 }
  26.                 break;
  27.             default:
  28.                 vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "Unknown");
  29.                 switch (Math.floor(nStatus / 100)) {
  30.                     case 1:
  31.                         console.log("Information code " + vMsg);
  32.                         break;
  33.                     case 2:
  34.                         console.log("Successful code " + vMsg);
  35.                         break;
  36.                     case 3:
  37.                         console.log("Redirection code " + vMsg);
  38.                         break;
  39.                     case 4:
  40.                         console.log("Client Error #" + vMsg);
  41.                         break;
  42.                     case 5:
  43.                         console.log("Server Error #" + vMsg);
  44.                         break;
  45.                     default:
  46.                         ajaxError();
  47.                 }
  48.         }
  49.         closeReq();
  50.     }
  51.     function filterURL (sURL, sViewMode) {
  52.         return sURL.replace(rSearch, "") + ("?" + sURL.replace(rHost, "&").replace(rView, sViewMode ? "&" + sViewKey + "=" + sViewMode : "").slice(1)).replace(rEndQstMark, "");
  53.     }
  54.     function getPage (sPage) {
  55.         if (bIsLoading) { return; }
  56.         oReq = new XMLHttpRequest();
  57.         bIsLoading = true;
  58.         oReq.onload = ajaxLoad;
  59.         oReq.onerror = ajaxError;
  60.         if (sPage) { oPageInfo.url = filterURL(sPage, null); }
  61.         oReq.open("get", filterURL(oPageInfo.url, "json"), true);
  62.         oReq.send();
  63.         oLoadingBox.parentNode || document.body.appendChild(oLoadingBox);
  64.     }
  65.     function requestPage (sURL) {
  66.         if (history.pushState) {
  67.             bUpdateURL = true;
  68.             getPage(sURL);
  69.         } else {
  70.             location.assign(sURL);
  71.         }
  72.     }
  73.     function processLink () {
  74.         if (this.className === sAjaxClass) {
  75.             requestPage(this.href);
  76.             return false;
  77.         }
  78.         return true;
  79.     }
  80.     function init () {
  81.         oPageInfo.title = document.title;
  82.         history.replaceState(oPageInfo, oPageInfo.title, oPageInfo.url);
  83.         for (var oLink, nIdx = 0, nLen = document.links.length; nIdx < nLen; document.links[nIdx++].onclick = processLink);
  84.     }
  85.     const sTargetId = "wrapper", sViewKey = "view_as", sAjaxClass = "goto",
  86.         rSearch = /\?.*$/, rHost = /^[^\?]*\?*&*/, rView = new RegExp("&" + sViewKey + "\\=[^&]*|&*$", "i"), rEndQstMark = /\?$/,
  87.         oLoadingBox = document.createElement("div"), oCover = document.createElement("div"), oLoadingSpin = document.createElement("div"),
  88.         oPageInfo = {
  89.             title: null,
  90.             url: location.href
  91.         }, oHTTPStatus = {
  92.             100: "Continue",
  93.             101: "Switching Protocols",
  94.             102: "Processing",
  95.             200: "OK",
  96.             201: "Created",
  97.             202: "Accepted",
  98.             203: "Non-Authoritative Information",
  99.             204: "No Content",
  100.             205: "Reset Content",
  101.             206: "Partial Content",
  102.             207: "Multi-Status",
  103.             208: "Already Reported",
  104.             226: "IM Used",
  105.             300: "Multiple Choices",
  106.             301: "Moved Permanently",
  107.             302: "Found",
  108.             303: "See Other",
  109.             304: "Not Modified",
  110.             305: "Use Proxy",
  111.             306: "Reserved",
  112.             307: "Temporary Redirect",
  113.             308: "Permanent Redirect",
  114.             400: "Bad Request",
  115.             401: "Unauthorized",
  116.             402: "Payment Required",
  117.             403: "Forbidden",
  118.             404: "Not Found",
  119.             405: "Method Not Allowed",
  120.             406: "Not Acceptable",
  121.             407: "Proxy Authentication Required",
  122.             408: "Request Timeout",
  123.             409: "Conflict",
  124.             410: "Gone",
  125.             411: "Length Required",
  126.             412: "Precondition Failed",
  127.             413: "Request Entity Too Large",
  128.             414: "Request-URI Too Long",
  129.             415: "Unsupported Media Type",
  130.             416: "Requested Range Not Satisfiable",
  131.             417: "Expectation Failed",
  132.             422: "Unprocessable Entity",
  133.             423: "Locked",
  134.             424: "Failed Dependency",
  135.             425: "Unassigned",
  136.             426: "Upgrade Required",
  137.             427: "Unassigned",
  138.             428: "Precondition Required",
  139.             429: "Too Many Requests",
  140.             430: "Unassigned",
  141.             431: "Request Header Fields Too Large",
  142.             500: "Internal Server Error",
  143.             501: "Not Implemented",
  144.             502: "Bad Gateway",
  145.             503: "Service Unavailable",
  146.             504: "Gateway Timeout",
  147.             505: "HTTP Version Not Supported",
  148.             506: "Variant Also Negotiates (Experimental)",
  149.             507: "Insufficient Storage",
  150.             508: "Loop Detected",
  151.             509: "Unassigned",
  152.             510: "Not Extended",
  153.             511: "Network Authentication Required"
  154.         };
  155.     var oReq, bIsLoading = false, bUpdateURL = false;
  156.     oLoadingBox.id = "loader";
  157.     oCover.className = "progress red accent-1";
  158.     oLoadingSpin.className = "indeterminate red darken-2";
  159.     oCover.onclick = abortReq;
  160.     oCover.appendChild(oLoadingSpin);
  161.     oLoadingBox.appendChild(oCover);
  162.     onpopstate = function (oEvent) {
  163.         bUpdateURL = false;
  164.         oPageInfo.title = oEvent.state.title;
  165.         oPageInfo.url = oEvent.state.url;
  166.         getPage();
  167.     };
  168.     window.addEventListener ? addEventListener("load", init, false) : window.attachEvent ? attachEvent("onload", init) : (onload = init);
  169.     this.open = requestPage;
  170.     this.stop = abortReq;
  171.     this.rebuildLinks = init;
  172. })();

Además tengo la sospecha de que no solo esos elementos se verán afectados. también inputs y cosas así.
Espero me puedan ayudar, muchas gracias de antemano y si necesitan algo más, por favor háganmelo saber.

Última edición por Silenn; 11/05/2018 a las 23:04
  #2 (permalink)  
Antiguo 12/05/2018, 09:45
Colaborador
 
Fecha de Ingreso: mayo-2008
Ubicación: $MX['VZ']['Xalapa']
Mensajes: 3.005
Antigüedad: 15 años, 11 meses
Puntos: 528
Respuesta: Navegación mediante AJAX

Supongo que se debe a que cuando tu servidor responde estás "dibujando" el html, pero no ejecutas el javascript si es que el contenido lo requiere.

Hay varias formas de abordar el problema, aunque lo más simple es hacer un eval() al contenido retornado por el servidor, sólo deberías tener una forma de identificar cuándo estás devolviendo html y cuándo javascript.
  #3 (permalink)  
Antiguo 12/05/2018, 13:06
 
Fecha de Ingreso: julio-2015
Ubicación: Distrito Federal
Mensajes: 97
Antigüedad: 8 años, 9 meses
Puntos: 2
Respuesta: Navegación mediante AJAX

Exactamente cómo debo hacer eso, estuve leyendo sobre eval() y hasta donde leí su funcionamiento se basa en evaluar ahora sí, la situación con el string del que se le llama.
  #4 (permalink)  
Antiguo 14/05/2018, 11:26
Colaborador
 
Fecha de Ingreso: mayo-2008
Ubicación: $MX['VZ']['Xalapa']
Mensajes: 3.005
Antigüedad: 15 años, 11 meses
Puntos: 528
Respuesta: Navegación mediante AJAX

Yo hice una función a la que le retorno SIEMPRE un json, el json contiene un arreglo que sólo puede tener dos posibles respuestas, html o javascript.

Si la respuesta es javascript, se ejecuta, si es html, se dibuja en el contener indicado, ejemplo:

Código Javascript:
Ver original
  1. respuesta=[
  2.    {"script":"codigo javascript"},
  3.    {"encabezado":"html que va a ir en el encabezado"}
  4. ]

Así, cuando recibo la etiqueta "script" la ejecuto con eval, si recibo cualquier otra cosa, asumo que es el id de un ekemento al que le voy a insertar el html.

Dado que te sería difícil cambiar lo que tienes a esta metodología, te sugiero que en donde recibes la respuesta ajax, podrías poner una condición, que si la respuesta contiene cierta palabra, le haces el eval, si no, lo que siempre haces.

Etiquetas: ajax, funcion, mediante, php
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 23:26.