简体   繁体   English

我需要将函数中的 java-script 变量的值分配给同一文件中的 php 变量

[英]I need to assign a value of java-script variable inside in function into php variable in a same file

I need to get the total value inside the computeTotalDistance() function into php variable.我需要将 computeTotalDistance() 函数中的总值放入 php 变量中。 I tried it many ways but was pointless.我尝试了很多方法,但毫无意义。

            var rendererOptions = {
                draggable: true
            };
            var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
            ;
            var directionsService = new google.maps.DirectionsService();
            var map;

            var Srilanka = new google.maps.LatLng(6.9344, 79.8428);

            function initialize() {

                var mapOptions = {
                    zoom: 8,
                    center: Srilanka
                };
                map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
                directionsDisplay.setMap(map);

                google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
                    computeTotalDistance(directionsDisplay.getDirections());
                });

                calcRoute();
            }

            function calcRoute() {

                var locations = ['Galle', 'Kandy', 'minneriya wildlife park', 'Horton Plains'];

                var waypoints = locations.map(function(loc) {
                    return { 'location': loc };
                });

                var request = {
                    origin: 'Colombo',
                    destination: 'Colombo',
                    waypoints: waypoints,
                    travelMode: google.maps.TravelMode.DRIVING
                };


                directionsService.route(request, function(response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                    }
                });
            }

            function computeTotalDistance(result) {
                var total = 0;
                var myroute = result.routes[0];
                for (var i = 0; i < myroute.legs.length; i++) {
                    total += myroute.legs[i].distance.value;
                }
                total = total / 1000.0;
                document.getElementById('total').innerHTML = total + ' km';
            }

            google.maps.event.addDomListener(window, 'load', initialize);

        </script>

I used following one, but I confused with how to catch return value with it.我使用了以下一个,但我对如何用它捕获返回值感到困惑。

 <?php
      $tot = echo "<script>document.writeln();</script>";
  ?> 

how could I assign this total distance value in to $tot value.我如何将这个总距离值分配给 $tot 值。

You are getting confused by two languages being present.您对存在的两种语言感到困惑。 You forget that your Javascript will run on the client, in the browser.您忘记了您的 Javascript 将在客户端的浏览器中运行。 PHP will run on the server. PHP 将在服务器上运行。 The only way to get the JavaScript value to your server is to HTTP POST/GET it to the server, using a hidden field in a HTTP form or an via ajax call.将 JavaScript 值获取到您的服务器的唯一方法是使用 HTTP 表单中的隐藏字段或通过 ajax 调用通过 HTTP POST/GET 将其发送到服务器。

Only way I can think of is to use JavaScript to send the URL back with a parameter in it such as:我能想到的唯一方法是使用 JavaScript 将带有参数的 URL 发回,例如:

http://www.example.com/index.php?id=1 http://www.example.com/index.php?id=1

... By using something like this, you can apply it in JavaScript: ...通过使用这样的东西,你可以在 JavaScript 中应用它:

window.location.href="index.php?value=1";

Then in the PHP code use $_GET :然后在 PHP 代码中使用$_GET

$somevar = $_GET["value"]; //puts the uid varialbe into $somevar

The JavaScript we are presented with here is client-side...我们在这里展示的 JavaScript 是客户端...

Since PHP is on the server-side level, we'd have to reach for it via HTTP requests.由于 PHP 处于服务器端级别,因此我们必须通过 HTTP 请求访问它。 HTTP requests is basically communication between the client and server. HTTP 请求基本上是客户端和服务器之间的通信。

JavaScript had a handly little library implemented into it called Ajax, which stands for Asynchronous JavaScript and XML (XML isn't really important here). JavaScript 中实现了一个名为 Ajax 的小库,它代表异步JavaScript 和XML (XML 在这里并不重要)。

Ajax allows us to perform HTTP requests asynchronously with in the script, and use the response that the server has as well. Ajax 允许我们在脚本中异步执行 HTTP 请求,并使用服务器的响应。

To make thing's syntactically more understandable, I'll be using jQuery, which provides an easy-to-use Ajax library ...为了使事情在语法上更易于理解,我将使用jQuery,它提供了一个易于使用的 Ajax 库......

With this provided, you can construct a request and also handle the response fairly easily...... Lets try this for example:有了这个,你就可以构建一个请求并相当容易地处理响应......让我们试试这个,例如:

$.ajax({
  "url": "index.php",
  "type": "POST",
  "data": {"testing":true},
  "success": function(response){
    console.log(response);
  }
});

This provided, we take our index.php file, and say we had the following code:这提供了我们的index.php文件,并说我们有以下代码:

<?php
  if(isset($_POST["testing"])) {
    echo $_POST["testing"] ? "Hello" : "Goodbye";    
  }
?>

Now back to the Ajax function.... In the "success" handler, we tell it to log whatever the response is.... Since our PHP is designed to say either "Hello" or "Goodbye" based on the value of the "testing" data we sent, this would provide a pretty straight-forward response... And in our case, it would log "Hello" .现在回到 Ajax 函数......在"success"处理程序中,我们告诉它记录任何响应......因为我们的 PHP 被设计为基于值说"Hello""Goodbye"我们发送的"testing"数据,这将提供一个非常直接的响应......在我们的例子中,它会记录"Hello"

That shows how you can create a relationship between the client and server through Ajax, allowing us to exchange data back and forth more easily.这展示了如何通过 Ajax 在客户端和服务器之间创建关系,使我们能够更轻松地来回交换数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM