将 JS 变量传递给 PHP 变量

IT技术 php javascript
2021-01-21 18:10:33

我有一个由 Google 地图给出的 JavaScript 值,我需要将它保存在 MySQL 数据库中。

其实我有变量

<script>
...
var lugar = results[0].geometry.location;// this gives me a latitud, longitud value, like: -34.397, 150.644
...
</script>

我需要将该变量传递给 PHP 变量 lugar

<?
$lugar= ?????
?>
4个回答

您可以为此使用 jQuery ajax,但您需要创建另一个脚本以保存在您的数据库中:

<script>
$.ajax({
    url: "save.in.my.database.php",
    type: "post",
    dataType:"json",
    data: {
        lugar: results[0].geometry.location
    },
    success: function(data){
        alert('saved');
    },
    error: function(){
        alert('error');
    }
});
</script>

“save.in.my.database.php”收到一个$_POST['lugar'],您可以保存在您的数据库中。

您需要通过表单提交、cookie 或通过查询字符串传递它。

POST如果您在页面转换时执行此操作,则可以通过表单或在 URL 中传递它,然后只需使用$_POST$_GET接收变量。

如果您需要无缝完成,那么您可能需要考虑使用 AJAX。 TIZAG AJAX 教程

这会将 js 变量转换为 php 变量

<script>
function sud(){

javavar=document.getElementById("text").value;  

document.getElementById("rslt").innerHTML="<?php 
$phpvar='"+javavar+"'; 
echo $phpvar.$phpvar;?>";
}

function sud2(){
document.getElementById("rslt2").innerHTML="<?php 
echo $phpvar;?>";
}

</script> 
<body>
<div id="rslt">
</div>

<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>

</body>

演示:http : //ibence.com/new.php