簡體   English   中英

Ajax / php標題:位置

[英]Ajax/php header:Location

我有一個帶有Ajax登錄表單的Bootstrap模式。 顯示錯誤,一切正常,直到login.php的結果為header('Location: index.php');

我處理這樣的結果:

var hr = new XMLHttpRequest();
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            document.getElementById("status").innerHTML = return_data;
        }
    }

問題是登錄成功后我得到了header('Location: index.php'); 響應index.phpdiv.status打開。

有沒有一種簡單的方法將PHP標頭轉換為javascript中的重定向?

您可以檢測請求是否是ajax請求。 如果它返回一個具有所需位置的json對象,否則執行典型的php重定向。

<?php   
    function isAjax() {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }

    if(isAjax()) {
        echo json_encode(array("location" => "index.php"));
    } else {
        header("Location: index.php");
    }
?>

一旦你在javascript中重新獲得json對象,用戶就會重定向

document.location = json.location;

您應該使用javascript重寫document.location而不是發送HTTP標頭。 它將為用戶提供與完整頁面請求的傳統重定向響應相同的基本體驗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM