2017-08-02 145 views
0

我想在我的着陸頁上製作一個函數,獲取用戶位置並計算出最近的商店並將其顯示在頁面上..我使用此代碼計算..將數據從javascript傳遞到php在同一頁

var cities = [ 
    ["city1", 10, 50, "blah"], 
    ["city2", 40, 60, "blah"], 
    ["city3", 25, 10, "blah"], 
]; 

function NearestCity(latitude, longitude) { 
    var mindif = 99999; 
    var closest; 

for (index = 0; index < cities.length; ++index) { 
    var dif = PythagorasEquirectangular(latitude, longitude, cities[index][1], cities[index][2]); 
    if (dif < mindif) { 
    closest = index; 
    mindif = dif; 
    } 
} 

    alert(cities[closest]); 
} 

如何將結果傳遞給php並存儲到數據庫?

+4

使用ajax調用將數據從javascript傳遞到php。 – Shubham

+0

如果您提到了標籤'php',那麼您的php代碼是什麼? – Virb

+0

將其發佈到php文件將是一個選項。基本上'僞造'一個表單,其中javascript的帖子就好像它是表單數據一樣。 PHP可以在它的$ _POST var中選擇它。看看ajax發佈和php表單基礎知識。 – Sk446

回答

0

所以你的標題是 - 從JavaScript 將數據傳遞給在同一頁面

PHP的如果將有可能網絡的發展已經改變了很多。 Javascript是一種客戶端編程語言。 和php是一種服務器端編程語言。

您無法在不重新加載的情況下將數據傳遞給php。

您將不得不使用ajax將數據傳遞給php,但爲此您必須製作不同的php頁面,而不是在同一頁面中。

But if you still wants to pass data from javascript to the same page, you will have to reload the page. 
- pass data to the hidden field 
- by javascript automatically post the form 
- page will reload and you will get the result in $_POST in a same page 
(but not a good way.) 
+0

不正確 - 你可以通過ajax發送數據到同一頁 – RamRaider

+0

那是怎麼回事?請給我們一個代碼....只需發送給我們一個代碼,在不刷新頁面的情況下,將JavaScript可變數據傳遞到php中。 – Farsay

0

您需要向PHP頁面發出AJAX請求。

var xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
    document.getElementById("demo").innerHTML = this.responseText; 
    } 
    }; 
    xhttp.open("POST", "abc.php", true); 
    xhttp.send("mindif="+mindif+"&&closest="+closest); 

在計算出該值後,將其添加到函數的末尾。 快速參考 - Ajax Javascript

0

計算後,您可以通過Ajax請求發送數據:

$.ajax({ 
    method: "POST", 
    url: "some.php", 
    data: { name: "John", location: "Boston" } 
}) 
.done(function(msg) { 
    alert("Data Saved: " + msg); 
}); 

click here for more detail

0

要從NearestCity功能,您通常會使用AJAX傳遞數據 - 可以對請求進行到相同的頁面或另一個取決於您自己的喜好。下面顯示瞭如何將數據發送到您的PHP代碼所使用的同一頁面 - 在這種情況下,它不會將信息保存到數據庫,但它可以非常輕鬆地完成。

<?php 
    if($_SERVER['REQUEST_METHOD']=='POST'){ 
     ob_clean(); 

     /* read and process ajax post request - available through the "$_POST" array */ 

     /* add to db or whatever */ 

     /* 
      send response to ajax callback 
      Here it is just a simple output showing the data that was sent via POST 
      but should be more meaningful ~ perhaps db results or html content etc 
     */ 
     echo implode(PHP_EOL, $_POST); 

     exit(); 
    } 
?> 
<!doctype html> 
<html> 
    <head> 
     <title>Find nearest - send via ajax to same page</title> 
     <script> 
      var defaults={ 
       lat:52.628593, 
       lng:1.296380 
      }; 

      var cities = [ 
       ['Aylsham', 52.794847, 1.252565, 'Aylsham is a historic market town and civil parish on the River Bure in north Norfolk, England'], 
       ['North Walsham', 52.823477, 1.390931, 'North Walsham is a market town and civil parish in Norfolk, England within the North Norfolk district'], 
       ['Dereham', 52.681311, 0.939737, 'Dereham, also known as East Dereham, is a town and civil parish in the English county of Norfolk'], 
       ['Cambridge',52.204548, 0.124404,'Cambridge is a city on the River Cam in eastern England, home to the prestigious University of Cambridge, dating to 1209'], 
       ['Swanton Morley',52.714710, 0.986908,'Swanton Morley is a village and civil parish situated in the English county of Norfolk'] 
      ]; 

      function Deg2Rad(deg) { 
       return deg * Math.PI/180; 
      } 

      function PythagorasEquirectangular(lat1, lon1, lat2, lon2) { 
       lat1 = Deg2Rad(lat1); 
       lat2 = Deg2Rad(lat2); 
       lon1 = Deg2Rad(lon1); 
       lon2 = Deg2Rad(lon2); 
       var R = 6371; // km 
       var x = (lon2 - lon1) * Math.cos((lat1 + lat2)/2); 
       var y = (lat2 - lat1); 
       var d = Math.sqrt(x * x + y * y) * R; 
       return d; 
      } 

      function NearestCity(_latitude, _longitude) { 
       var mindif = 99999; 
       var closest; 
       var tmp=[]; 

       console.info('Find nearest city based upon lat:%s and lng:%s',_latitude, _longitude); 

       for (var i=0; i < cities.length; i++) { 
        var _lat=cities[i][1]; 
        var _lng=cities[i][2]; 

        var difference = PythagorasEquirectangular(_latitude, _longitude, _lat, _lng); 

        if(difference < mindif) { 
         closest = i; 
         mindif = difference; 
         tmp.push(cities[ i ]); 
        } 
       } 

       /* send request to the same page! */ 
       ajax.call(this, location.href, tmp, cbNearestCity); 
      } 

      function ajax(url, params, callback){ 
       var xhr=new XMLHttpRequest(); 
       xhr.onreadystatechange=function(){ 
        if(xhr.readyState==4 && xhr.status==200){ 
         callback.call(this, this.response); 
        } 
       }; 
       var payload=[]; 
       for(var n in params)payload.push(params[n][0]+'='+params[n]); 

       xhr.open('post', url, true); 
       xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
       xhr.setRequestHeader('X-Requested-With','XMLHttpRequest'); 
       xhr.send(payload.join('&')); 
      } 

      function cbNearestCity(response){ 
       document.getElementById('results').innerHTML=response; 
      } 



      document.addEventListener('DOMContentLoaded',function(e){ 
       if(navigator.geolocation){ 
        navigator.geolocation.getCurrentPosition(function(pos){ 
         NearestCity.call(this, pos.coords.latitude, pos.coords.longitude); 
        }); 
       } else { 
        NearestCity.call(this, defaults.lat, defaults.lng); 
       } 
      },{ capture:false, passive:true }); 
     </script> 
    </head> 
    <body> 
     <h1>Find nearest city - using geolocation on page load</h1> 
     <pre id='results'></pre> 
    </body> 
</html>