gpt4 book ai didi

javascript - 如何在javascript中传递 session 变量

转载 作者:行者123 更新时间:2023-12-02 16:14:40 24 4
gpt4 key购买 nike

我是 php 新手...我为 html 编写了 javascript..但我不知道如何使用该 session 值将相同的 javascript 概念写入 php..

我的 session 值:

$_SESSION['line2'],

$_SESSION['oline2']

我的 JavaScript 代码在这里:

function showLocation() {
var geocoder, location1, location2, gDir;

geocoder = new GClientGeocoder();
gDir = new GDirections();
GEvent.addListener(gDir, "load", function() {
//var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
// var miles = drivingDistanceMiles ;
var km = drivingDistanceKilometers;
//document.getElementById('miles').value = miles;
document.getElementById('km').value = km;

});

geocoder.getLocations(document.getElementsByName("addressline2")[0].value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the first address");
}
else
{
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
geocoder.getLocations(document.getElementsByName("officeaddressline2")[0].value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the second address");
}
else
{
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
gDir.load('from: ' + location1.address + ' to: ' + location2.address);
}
});
}
});
}

大家帮忙

最佳答案

如果您将该 JavaScript 函数与 PHP 文件一起使用,则可以这样做:

...
var line2 = '<?php echo $_SESSION["line2"]; ?>';
var oline2 = '<?php echo $_SESSION["oline2"]; ?>';
...

要将 JavaScript 变量传递给 PHP,您必须执行以下步骤:

  1. 包括JQuery Library在您的页面中(如果您还没有)。
  2. 创建一个 PHP 页面来设置变量(即:myPage.php)。
  3. 通过 POST 使用 ajax (JQuery) 将 JS 变量传递到 myPage.php。

myPage.php:

<?php
session_start();

$_SESSION['line2'] = $_POST['myVariable'];
$_SESSION['oline2'] = $_POST['anotherOne'];
...

在你的 JS 函数中:

var sth = 'something...';
var sthMore = 'something more...';

$.ajax({
method: "POST",
url: "myPage.php",
data: { myVariable: sth, anotherOne: sthMore }
}).done(function() {
// alert('done!'); // here you can alert some message (if you want)
});

关于javascript - 如何在javascript中传递 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29795058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com