基于AJAX的网站中的JS window.location

JS window.location in an AJAX based site

本文关键字:window location JS 网站 AJAX 基于      更新时间:2023-09-26

我有一个简单的基于AJAX的网站,我有同样简单的地理定位功能,当用户点击按钮时,它会将用户重定向到新页面。

这是我的地理定位功能的一部分,它重定向用户,正如你所看到的,它将人们重定向到一个名为weather.php的页面;

function showPosition(position) {
    window.location='weather.php?lat='+position.coords.latitude+'&long='+position.coords.longitude;
}

问题是,它使用"传统"页面加载重定向页面,从而使我实现的AJAX页面加载过时。

有可能修改这个函数并使其对AJAX友好吗?

这是完整的重定向代码;

<button onclick="getLocation()">My Location</button>
    <script>
        var x = document.getElementById("message");
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            } else {
                x.innerHTML = "Geolocation is not supported by this browser.";
            }
        }
        function showPosition(position) {
            window.location='weather.php?lat='+position.coords.latitude+'&long='+position.coords.longitude;
        }
    <script>

以下是如何做到这一点。我给您举一个简单的网站示例,其中页面是用Ajax加载的。页面被放在url中。

不是这样的:weather.php?lat=50.452

但是像这样:index.php#50.452

关键是:当您更改#右侧的任何内容时,页面不会重新加载。尽管如此,还是有一个系统,url会记住页面

这不是你问题的完整答案,但我希望它能给你所需的灵感

pages.php

<?php
switch(isset($_GET['p']) ? $_GET['p'] : '') {
  default:
    $content = 'This is the HOME page ...';
    break;
  case 'calendar':
    $content = 'calendar stuff ...';
    break;
  case 'contact':
    $content = 'contact stuff ...';
    break;
}
echo $content;
?>

index.php

<!DOCTYPE html>
<html>
<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script>
  // load page according to the url.
  //  We read the url, to the right hand side of the # (hash symbol)
  var hash = window.location.hash;
  var page = hash.substr(1);  // this removes the first character (the #)
  loadPage(page);
  // triggered by the navigation.
  function loadPage(page) {
    getAjaxPage(page);
  }
  // this returns the content of a page
  function getAjaxPage(page) {
    switch (page) {
      default: // = HOME page
        var url = '';
      case 'calendar':
      case 'contact':
        var url = page;
    }
    $.ajax({
      url: 'pages.php',
      data: {
        p: url
      },
      success: function(data) {
        $('#content').html(data);
      }
    })
  }
  </script>
  <style>
    #content {
      margin: 15px;
    }
  </style>
</head>
<body>
  <div id="nav">
    <a href="#" onclick="loadPage('')">Home</a> |
    <a href="#calendar" onclick="loadPage('calendar')">Calendar</a> |
    <a href="#contact" onclick="loadPage('contact')">Contact</a> |
  </div>
  <div id="content"></div>
</body>
</html>

你的工作。。。您不应该重定向客户端
这(有点像)谷歌地图的东西,对吧?你的意图是什么?

为什么不能用Ajax加载weather.php?我打赌你能。