将JS变量传递给PHP变量

时间:2011-01-17 17:52:37

标签: php javascript

我有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 个答案:

答案 0 :(得分:3)

您可以使用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'],您可以保存在数据库中。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

如果您需要无缝完成,那么您可能希望使用AJAX。 TIZAG AJAX Tutorial

答案 3 :(得分:0)

这会将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

相关问题