Я использую Jquery для загрузки динамических данных php в мой файл, но не могу сохранить данные в переменных Javascript - PullRequest
0 голосов
/ 25 апреля 2018

В моем файле 'retrievedata.php' я распечатываю динамически обновляемые абзацы широты и долготы.Это работает нормально:

<html>
  <body>
    <p id="userlatlng"> {lat: <?php echo $lat ?>, lng: <?php echo $lng ?> } </p>
  </body>
</html>

В моем другом файле, чтобы отобразить эти точки на Google Картах, я изо всех сил стараюсь сохранить данные из файла 'retrievedata.php' в переменные Javascript.Javascript не позволит мне получить getElementByID в этом случае, и я не знаю, как решить эту проблему.

   <html>
  <head>
    <link href="style.css" rel="stylesheet" type="text/css"></link>
    <link rel="icon" href="images/favicon.png">
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <div id="map"></div>
    <input type="button" id="display" value="Display All Data" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>

      $(document).ready(function() {
        $(function retrieveData(){
        $.ajax({    //create an ajax request to display.php
          type: "GET",
          url: "retrievedata.php",
          dataType: "html",   //expect html to be returned
          success: function(response){
              $("#responsecontainer").html(response);
          }
          });
          timerId = setTimeout(retrieveData, 1000);
        });
      });

      </script>

      <p id="responsecontainer"></p>
      <h2 id="userlatlngtest">test</h2>

      <script>
      var response = document.getElementById("responsecontainer").innerHTML;

      function initMap() {
          var leeds = {lat: 53.807081, lng: -1.555848};
          map = new google.maps.Map(document.getElementById('map'), {
              center: leeds,
              zoom: 16
          });

          var marker = new google.maps.Marker({
                    position: userlat,
                    map: map,
                  });

      }

    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXB2UeKrP80RfU-webxxV757b3j9vubcc&callback=initMap">
    </script>

  </body>
</html>

Ответы [ 2 ]

0 голосов
/ 29 апреля 2018

У меня это работает. Возник ряд проблем, в том числе то, что у меня был HTML в моем файле db_connect.php.

Вот рабочий код php:

<?php
/*
  require_once("db_connect.php");
*/
  $db_hostname = 'xxxxxxxxx';
    $db_database = 'xxxxxxxx'; //'Your database name'
    $db_username = 'xxxxxxxxxx'; //'username';
    $db_password = 'xxxxxxxxxx'; //'password';
    $db_status = 'not initialised';
    $db_server = mysqli_connect($db_hostname, $db_username, $db_password);
    $db_status = "connected";

    if (!$db_server){
        die("Unable to connect to MySQL: " . mysqli_connect_error());
        $db_status = "not connected";
    }


  mysqli_select_db($db_server, $db_database) or die("Couldn't find db");
  $query = "SELECT * FROM locations WHERE ID = 1";
  $result = mysqli_query($db_server, $query);
  if(!$result) die('Query failed: ' . mysqli_error($db_server));

  $str_result = mysqli_num_rows($result). "rows<br />";
  while($row = mysqli_fetch_array($result)){
    $lat = $row['lat'] ;
    $lng = $row['lng'] ;
  }


 echo $lat . "," .  $lng ?>

И в файле для построения местоположения точки:

<!DOCTYPE html>
<html>
<head>
    <title>Location tracking Google map</title>
</head>
<body>
    <h1>Location tracking Google Map</h1>

    <!-- testing, next 3 lines can be removed -->
    <h4>Testing variables (these latlngs have no effect on the map):</h4>
    <p id="responsecontainer"></p>
    <p id="responsecheck"></p>

    <!-- the map -->
    <div id="map" style="width:600px;height:400px">My map will go here</div>

</body>
</html>

<!-- the scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    //Global variables for map and marker
    var map;
    var marker;
    //function to set uo the map
    function myMap() {
        var mapOptions = {
            center: new google.maps.LatLng(51.5, -0.12),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.HYBRID
        }
        map = new google.maps.Map(document.getElementById("map"), mapOptions);
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(51.5, -0.12),
            map: map,
            title: 'Initial marker!'
          });
    }
    //jQuery and ajax call to get new location location
    $(document).ready(function() {
        $(function retrieveData(){
           $.ajax({    //create an ajax request to display.php
              type: "GET",
              url: "retrievedata.php",
              dataType: "html",   //expect html to be returned
              success: function(response){

                  var res = response.split(",");
                  myLat = res[0];
                  myLng = res[1];
                  point = new google.maps.LatLng(myLat, myLng);
                  map.setCenter(point);
                  changeMarkerPosition(marker, point);

                  //testing - next two lines can be removed
                  $("#responsecontainer").html(response);
                  $("#responsecheck").html("myLat: " + myLat + ", myLng: " + myLng);
              }
          });
          timerId = setTimeout(retrieveData, 1000);
        });
    });
    //function to update marker location on map
    function changeMarkerPosition(mymarker, location){
        mymarker.setPosition(location);
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIsCXBsss2UeKrP80RfU-webxxV757b3j9vubcc&callback=myMap"></script>
0 голосов
/ 25 апреля 2018

Отправить вывод json и проанализировать его в вызове ajax

<?php
header( 'Content-Type: application/json' );
echo json_encode(array('lat'=> $lat, 'lng'=> $lng));

Тогда ваш HTML становится

<html>
    <head>
        <link href="style.css" rel="stylesheet" type="text/css"></link>
        <link rel="icon" href="images/favicon.png">
        <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    </head>
    <body>
        <div id="map"></div>
        <input type="button" id="display" value="Display All Data" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

        <h2 id="userlatlngtest">test</h2>


        <script>
            function initMap() {
                var leeds = {lat: 53.807081, lng: -1.555848};
                var map, marker;
                map = new google.maps.Map(document.getElementById('map'), {
                    center: leeds,
                    zoom: 16
                });
                $.ajax({
                    type: "GET",
                    url: "retrievedata.php",
                    success: function (response) {
                        marker = new google.maps.Marker({
                            position: response,
                            map: map,
                        });
                    }
                });
            }
        </script>
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXB2UeKrP80RfU-webxxV757b3j9vubcc&callback=initMap">
        </script>

    </body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...