通过PHP表单传递Javascript和PHP变量

Pass Javascript and PHP variables through PHP Form

本文关键字:PHP 变量 Javascript 表单 通过      更新时间:2023-09-26

搜索了一整天,找到了相似但完全卡住的项目。。。

我想通过一个提交(而不是两个按钮,即将JS变量放在隐藏字段中,然后通过提交按钮提交表单)将谷歌地图自动完成结果(latlng)与PHP变量一起传递到PHP表单中

目前代码:

    <?php    
if (isset($_POST['submit'])) {    
  // echo vars if they are working...
  echo "passed data <br>";
  echo $_POST['first_name'] . "<br>";
  echo $_POST['geocode'] . "<br>";    
  // Get variables, check data and store into DB...    
}    
?>

然后:

<script type="text/javascript">
  var geocoder;
  function initialize() {
    // Search options
    var searchOptions = { 
      componentRestrictions : {country: 'nz'},
      types: ['geocode']
    };
    var input = document.getElementById('pac-input');
    var autocomplete = new google.maps.places.Autocomplete(input, searchOptions);
    geocoder = new google.maps.Geocoder();
  }
  function codeAddress() {
    var address = document.getElementById('pac-input').value;
    geocoder.geocode( { 'address': address}, function(results, status) {    
      if (status == google.maps.GeocoderStatus.OK) {        
        document.getElementById('geocode').value = (results[0].geometry.location);             
      } else {
        //alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }
  google.maps.event.addDomListener(window, 'load', initialize); 
  function submitthis() {
    codeAddress();
  }
  </script>
  <script>
  $(function(){ // Document Ready
  });
  </script>

最后:

<form id="myForm" name="myForm" action="google-text-input.php" method="post" >
    First Name<input name="first_name" type="text"><br>
    Address<input id="pac-input" class="controls" type="text" placeholder="Search Box"><br>

    <input id="geocode" name="geocode" type="text" value="null"><br> <!-- to be hidden -->
    <input name="submit" type="submit" value="Submit" onclick="submitthis()"><br>

  </form>

我更希望当我点击提交按钮时,它会将谷歌地图结果存储到隐藏的页面中,将表单提交到同一页面,然后我可以提取所有php变量并进行存储。我对一种方法持开放态度,这种方法在提交时将javascript部分放入url中,在那里我可以通过POST提取PHP变量,并在url中获取Google结果。

我能看到的唯一不起作用的是在我的codeAddress()完成之前提交了表单。就好像我把return设为false以阻止表单提交一样,它会更新我的隐藏字段。

提前感谢!

老实说,我对谷歌的地理编码api不是很熟悉,但有几种方法可以做到这一点。

第一种方法

在表单中附加隐藏的输入元素。这可能与您在问题中描述的内容最接近。

这是一个简化的表格:

<form name="testForm" action="test.php" 
  method="post" onSubmit="return doSubmit();">
    <input type="submit" name="submit" />
</form>

添加return doSubmit();意味着您可以调用该函数,并在需要时取消发送表单。

这是附带的javascript:

function doSubmit() {
    var latval = 42; // Use the geolocation values you want here.
    var lat = document.createElement("input");
    lat.setAttribute("type", "hidden");
    lat.setAttribute("value", latval);
    lat.setAttribute("name", "geo[lat]");
    document.forms["testForm"].appendChild(lat);
    return true;
    //Note: to stop the form from submitting, you can just return false.
}

如果使用jQuery,这会变得更容易。您不需要在表单中添加onSubmit字段。只需为提交按钮指定一个唯一的名称或id即可。

$(document.ready(function() {
    $("input[name=submit]").click(function(e) {
       var latVal = 42; // Get geo vals here.
       $("form[name=testForm]").appendChild(
           "<input type='hidden' name='geo[lat]' value='" + latVal + "' />"
       );
    });

});

这里有一个简单的测试php文件:

//test.php
<?php
if (isset($_POST["geo"])) {
    echo "LAT IS: ".$_POST["geo"]["lat"];
}
?>

当您单击该按钮时,它将向表单附加一个隐藏的输入,并将其与其余POST数据一起发送。您可以将数组类型值分配给表单名称,它会将其转换为PHP $_POST数组中的数组。

当您单击按钮时,此示例将打印"LAT IS:42"。

第二种方法

这是最好的一个。在jQuery中使用ajax和json(ajax可以在原始javascript中完成,但这并不有趣!

为此,我将使用一个更简单的表单,并添加一个div:

<form name="testForm">
    <input type="submit" name="submit" />
</form>
<div id="output"></div>

php只是回声$_POST["geo"]["lat"]

这是javascript:

$(document).ready(function() {
    $("form[name=testForm]").submit(function (e) {
        // Prevent form from submitting.
        e.preventDefault();
        // Create a js object.
        var jso = {};
        // Add a geo object.
        jso['geo'] = {};
        // Define its lat value.
        jso['geo']['lat'] = 42;
        // Add all other values you want to POST in the method.
        // You can also just do jso.lat = 42, then change the php accordingly.
        // Send the ajax query.
        $.ajax({
            url: 'test.php',
            type: 'POST',
            data: jso,
            success: function(data, status) {
                $("#output").html("<p>" + data + "</p>"); 
            }
        });
    });
});

简而言之,ajax就是这么简单。在本例中单击submit按钮将把div的html设置为42。