PHP- Ajax and Redirect

前端 未结 3 611
情书的邮戳
情书的邮戳 2020-12-11 12:33

i have a jquery Ajax request happening on a page. On php side i am checking if the session is active and doing something. If the session is not active i want to redirect th

相关标签:
3条回答
  • 2020-12-11 12:47

    Redirects only say "The data you requested can be found here".

    HTTP provides no way to say "Even though you requested a resource to go inside a page, you should should leave that page and go somewhere else".

    You need to return a response that your JavaScript understands to mean "Go to a different location" and process it in your own code.

    0 讨论(0)
  • 2020-12-11 13:06

    If I understand what you want to happen then this is how I'm implementing it. It's in Prototype instead of jQuery but it shouldn't take you long to translate:

    new Ajax.Request('process.php', {
        on401: function(response) {
            var redirect = response.getHeader('Location');
            document.location = redirect;
        }
    });
    

    In your PHP, output the following if the session is inactive:

    header('Location: http://example.com/login.php', true, 401);
    exit;
    
    0 讨论(0)
  • 2020-12-11 13:06

    This is what you would want in your php IF THIS WERE A REGULAR REQUEST, NOT AN AJAX

    if (isset($_SESSION)) doSomething();  
    else header("Location: otherUrl");
    

    Since this is an Ajax call, you are not passing control to the php, but just trying to get a response that (likely) fills a particular section of your page. You do not mention what jQuery ajax function you use, but it matters. I would imagine you are using either $.get() or $(element).load() ??

    Without knowing the particulars, this is my best suggestion for you.

    Ajax call: $.get(url, callbackFunc);

    php:

    if(isset($_SESSION)) echoSomething()   else echo("redirect");
    

    callbackFunc:

    function(data)
    { if (data == "redirect") window.location = otherUrl;
       else 
       $("#desiredElement").html(data);
    }
    
    0 讨论(0)
提交回复
热议问题