2012-08-02 9 views
7

Estoy construyendo una aplicación JQuery Mobile basada en un framework MVC.Soporte para la redirección de página en Jquery mobile usando llamadas Ajax

Mi problema es que no puedo enviar directivas de "redirección" (ya sea HTTP, Javascript, META-refresh) al navegador.

Resulta en el navegador que muestra una sola línea: "undefined".

Este es el código para la redirección en el lado del servidor:

<html><head> 
     <script>location.href='$url'</script> 
</head></html> 

Sé que puedo solucionar el problema mediante el uso de data-ajax=false, pero yo no quiero eso desde:

  • Quiero buenas transiciones móviles Jquery
  • Esto es mucho más rápido en Ajax
  • No quiero preguntarme por cada enlace siempre que el marco pueda enviar una redirección

¿Hay alguna manera de hacer que JQuery Mobile maneje correctamente un tipo de redirección? ya sea HTTP, HTML META o Javascript?

+0

¿Qué tecnología del lado del servidor está utilizando? Deberías hacer el redireccionamiento allí. – Jasper

+0

Uso PHP. Y hago el redireccionamiento aquí. Es solo que las envolturas móviles de Jquery piensan con Ajax y no funcionan bien con la redirección estándar. –

+0

¿Qué problemas tienes? ¿Qué errores estás obteniendo? ¿Por qué estás redirigiendo? ¿Cómo se ve el código que crea la redirección? Esta es una pregunta vaga – Jasper

Respuesta

8

Con la ayuda del JQuery mobile community, he encontrado una solución elegante que puede manejar la redirección de HTML estándar (data-ajax="false") y las transiciones de página JQM.

El truco es que, al hacer transiciones JQM, JQM carga el resultado HTML con javascript; busca una página `data-role = 'page' y la reemplaza en el DOM: Ignora el encabezado HTML.

Por lo tanto, tenemos que poner una redirección de Javascript estándar en el encabezado y cargar una página de JQM en una página ficticia.

Este es el código del método de redirección en mi plantilla MVC:

<html> 
    <head> 
     <!-- HTML reload (for data-ajax=false) --> 
     <script> 
      location.href='<?= $url ?>' 
     </script> 
    </head> 
    <body> 
     <!-- Change page : JQueryMobile redirect --> 
     <div data-role="page" id="redirect"> 
      <script> 
       $.mobile.changePage('<?= $url ?>'); 
      </script> 
     </div> 
    </body> 
</html> 

espero que esto ayude a alguien.

+0

¿Es que no está pasando la url correctamente? su paso como '' no debe ser menos que me falta algo: p – BExDeath

+1

es un valor cabeza de serie a partir del código serverside –

+0

¿Alguna vez encontrar una mejor solución para esto? ¿O el soporte de framework mejoró para los redireccionamientos del lado del servidor? No quiero hacer esto si es redundante por alguna razón por ahora –

1

Parece que esta sería una mejor solución: de las demostraciones de jQuery Mobile.

Básicamente configura un encabezado http en su redirección y búsquelo en pagecontainerload. Esto debería evitar rarezas con el historial del navegador.

Aquí hay una a href para llegar a la página de

<a href="redirect.php?to=redirect-target.html" 
    data-role="button" data-inline="true">Redirect</a> 

En PHP hace esto

<?php 
// ************************************************************************ 
// The two-second sleep simulates network delays, hopefully causing a 
// loading indicator message to appear on the client side. 
// ************************************************************************ 
sleep(2); 

$dst = (isset($_GET[ "to" ]) 
    ? $_GET[ "to" ] 
    : (isset($_POST[ "to" ]) 
     ? $_POST[ "to" ] 
     : false)); 
if ($dst) { 
    // ********************************************************************** 
    // The crucial line: Issue a custom header with the location to which the 
    // redirect should happen. For simplicity, we simply redirect to whatever 
    // location was specified in the request's "to" parameter, but real-world 
    // scripts can compute the destination based on server-side state. 
    // 
    // NB: This is not a HTTP redirect. As far as HTTP is concerned, this is 
    // a normal request/response cycle with a status code of 200. 
    // ********************************************************************** 
    header("X-Redirect: " . $dst); 
} 
?> 

Luego, en su Javascript a hacer esto para interceptar la URL y reiniciarlo.

$(document).bind("pagecontainerload", function(e, triggerData) { 

     // We can use this event to recognize that this is a redirect. The event is 
     // triggered when jQuery Mobile has finished loading a page and inserting 
     // it into the DOM, but before it has altered the browser history. In this 
     // example the server helpfully returns a custom header. However, if you 
     // don't have access to the server side, you can still examine 
     // triggerData.page, which contains the page that was loaded, but which 
     // has not yet been displayed or even recorded in the browser history. You 
     // can also examine triggerData.xhr which contains the full XMLHTTPRequest. 
     // If there is a way to recognize that this is not the expected page, you 
     // can discard it and issue a second load() call for the page that really 
     // needs to be displayed to the user, reusing the options from the overall 
     // page change process. 

     var redirect = triggerData.xhr.getResponseHeader("X-Redirect"); 
     if (redirect) { 

      // We have identified that this page is really a redirect. Thus, we load 
      // the real page instead, reusing the options passed in. It is important 
      // to reuse the options, because they contain the deferred governing this 
      // page change process. We must also prevent the default on this event so 
      // that the page change process continues with the desired page. 
      $(e.target).pagecontainer("load", redirect, triggerData.options); 
      e.preventDefault(); 
     } 
    }); 

Nota: en el momento de la escritura que había un enlace roto en la página de demos de jQuery para esta demostración, así que tenía que encontrarla en github

https://github.com/jquery/jquery-mobile/blob/master/demos/navigation-php-redirect/index.php https://github.com/jquery/jquery-mobile/blob/master/demos/navigation-php-redirect/redirect.php

La demo de 1.3 es sigue trabajando http://demos.jquerymobile.com/1.3.0/docs/examples/redirect/

Cuestiones relacionadas