javascript - 在同一页面中将数据从 javascript 传递到 php

标签 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并存储到数据库?

最佳答案

要从 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>

关于javascript - 在同一页面中将数据从 javascript 传递到 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45453231/

相关文章:

javascript - Bootstrap Modal 中谷歌地图的灰色 map

javascript - 浏览器使用 AJAX + setInterval 不断占用内存

javascript - 错误类型错误: this.route.params.flatMap不是函数

php - 反转字符串中元音的位置

php - 从模数中获取特定行(php)

javascript - 如何修复 MetaMask 无法获取错误?

javascript - 通过 js 启用/禁用 aspx 验证器在代码隐藏中不成立?

javascript - 如何使用 Laravel 在 DataTable 中添加列并从数据库返回值

php - CodeIgniter将类加载到类中

php - iOS登录-此代码正确/安全吗?如何检查用户是否已经登录?