简体   繁体   English

将Ajax内容重定向到父页面

[英]Redirect ajax content to the parent page

On a webpage I have some content loaded via Ajax. 在网页上,我通过Ajax加载了一些内容。 If a user happens to visit the actual page that the ajax content is loaded from I want them to be redirected to the parent page itself. 如果用户碰巧访问了从中加载ajax内容的实际页面,我希望他们被重定向到父页面本身。 I thought I was being clever with the follow javascript, which works but seems dodgy and might break with a certain url: 我以为我对以下javascript很聪明,该javascript可以工作,但看起来有些晦涩,并且可能会破坏某些URL:

$url = top.location.href;

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

Is there a better way of doing this? 有更好的方法吗? If this is possible in PHP this would be preferable. 如果这在PHP中是可能的,那将是可取的。

Thanks! 谢谢!

Please try this: 请尝试以下方法:

events.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 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>

A different approach might be like: 一种不同的方法可能是:

events.php events.php

<?php

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

?>

Then you can request with $('.test').load('events.php?a'); 然后,您可以请求$('.test').load('events.php?a'); .

Note that the user is always able to see the events no matter what you do, if the javascript can do it, they can too. 请注意,无论您做什么,用户始终可以看到事件,如果JavaScript可以做到,那么他们也可以看到。

Try This: 尝试这个:

$.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