繁体   English   中英

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

[英]Pass Javascript and PHP variables through PHP Form

整天都在搜索,发现相似但完全卡住的物品...

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

目前的代码:

    <?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>

我希望当我单击“提交”按钮时,它会将Google Maps结果存储为隐藏,将表单提交到同一页面,然后可以拉出所有php vars并存储。 我愿意接受一种方法,提交后将javascript部分放到url中,我可以通过POST提取PHP变量,而只需在URL中获取Google结果。

我唯一可以看到的在上面无效的是在我的codeAddress()完成之前提交了表单。 好像我把return false阻止表单提交一样,它更新了我的隐藏字段。

提前致谢!

老实说,我对Google的Geocoding 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的简易性。 在此示例中,单击提交按钮会将div的html设置为42。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM