簡體   English   中英

將Ajax內容重定向到父頁面

[英]Redirect ajax content to the parent page

在網頁上,我通過Ajax加載了一些內容。 如果用戶碰巧訪問了從中加載ajax內容的實際頁面,我希望他們被重定向到父頁面本身。 我以為我對以下javascript很聰明,該javascript可以工作,但看起來有些晦澀,並且可能會破壞某些URL:

$url = top.location.href;

if($url.indexOf('/events/') <= 0){
    window.location = site_url + "events/?event=" + id;
}

有更好的方法嗎? 如果這在PHP中是可能的,那將是可取的。

謝謝!

請嘗試以下方法:

events.php

<?php

if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    header("Location: index.html");
    exit;
}
echo "There are no events to display.";

?>

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Events</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
    </head>
    <body>
        <div class="test"></div>
        <script>
            $('.test').load('events.php');
        </script>
    </body>
</html>

一種不同的方法可能是:

events.php

<?php

if (!isset($_GET['a'])) {
    header("Location: index.html");
    exit;
}
echo "There are no events to display.";

?>

然后,您可以請求$('.test').load('events.php?a');

請注意,無論您做什么,用戶始終可以看到事件,如果JavaScript可以做到,那么他們也可以看到。

嘗試這個:

$.ajax({
    type: "POST",
    url: reqUrl,
    data: reqBody,
    dataType: "json",
    success: function(data, textStatus) {
        if (data.redirect) {
            // data.redirect contains the string URL to redirect to
            window.location.href = data.redirect;
        }
        else {
             // data.form contains the HTML for the replacement form
            $("#myform").replaceWith(data.form);
        }
    }
}); 

暫無
暫無

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

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