【问题标题】:Pass a JS variable to a PHP variable将 JS 变量传递给 PHP 变量
【发布时间】:2011-01-17 17:52:36
【问题描述】:

我有一个由 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= ?????
?>

【问题讨论】:

标签: php javascript


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【解决方案3】:

    您可以通过表单POST 或在页面转换时在 URL 中传递它,然后只需使用$_POST$_GET 来接收变量。

    如果您需要无缝地完成它,那么您可能想考虑使用 AJAX。 TIZAG AJAX Tutorial

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-24
        • 2018-05-09
        • 2012-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多