代码之家  ›  专栏  ›  技术社区  ›  Suleman Khalid

我使用Jquery将动态php数据加载到文件中,但无法将数据存储到Javascript变量中

  •  0
  • Suleman Khalid  · 技术社区  · 7 年前

    在我的“检索数据”中。php文件,我正在打印动态更新的经纬度段落。这很好:

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

    在我的另一个在谷歌地图上绘制这些点的文件中,我正在努力存储“retrievedata”中的数据。php文件转换为Javascript变量。在这种情况下,Javascript不允许我获取ElementById,我不知道如何解决这个问题。

       <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 回复  |  直到 7 年前
        1
  •  0
  •   Rohit Agre    7 年前

    发送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>
    
        2
  •  0
  •   Suleman Khalid    7 年前

    我已经让它工作了。有很多问题,包括我的db\U connect中有HTML。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>