开发者

How to handle redirection in an Ajax based application

开发者 https://www.devze.com 2023-02-02 05:40 出处:网络
I\'m developing a Ajax based php application. As anybody knows, I\'m checking whether user is logged in every php file as the first statement. And there are two ways that I should response in an event

I'm developing a Ajax based php application. As anybody knows, I'm checking whether user is logged in every php file as the first statement. And there are two ways that I should response in an event of logging failure,

  1. server redirect to the login page using header(url). CASE: If user directly enter a particular URL

  2. passing url in Ajax response asking client side page redirection or notification CASE: If user trying to perform some action through 开发者_高级运维a Ajax request

So my question is how can identify whether request coming from client side is a Ajax call or not ? If I know that I can handle my response accordingly.

OR Is there a better way of handling above scenario ?

Thank You


It depends on how you are performing your ajax calls. It is good practice to set the following request header when sending an ajax request (most libraries like jQuery or prototype will do this for you):

'X-Requested-With' = 'XMLHttpRequest'

So you can check for that header on the server side and respond accordingly with a 302 redirect or a flag so the client javascript does the redirect.


In the client side you could parse the AJAX response and if it shows that the user needs to login, call window.location = LOGIN_PAGE_URL;

0

精彩评论

暂无评论...
验证码 换一张
取 消