繁体   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