在一个网页上,我有一些内容通过Ajax加载。如果用户碰巧访问了加载ajax内容的实际页面,我希望将它们重定向到父页面本身。我以为我是聪明的跟随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可以做到,他们也可以。
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);
}
}
});