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

时间:2015-03-24 08:24:56

标签: javascript ajax geolocation

我有一个简单的基于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>

1 个答案:

答案 0 :(得分:0)

以下是如何做到这一点。 我给你一个网站的简单例子,其中页面加载了Ajax。该页面放在网址中。

不喜欢这样:weather.php?lat = 50.452

但是像这样:index.php#50.452

重点是:当您更改#的任何内容时,页面不会重新加载。 而且,有一个系统,网址会记住页面

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

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?我打赌你可以。

相关问题