繁体   English   中英

将 PHP 变量从 HTML 表单传递到 Javascript

[英]Pass PHP variable from HTML form to Javascript

你能帮我把一个从 html 表格中取出的变量传递给 javascript 吗?

表格要求输入表名

  <br>
    New tablename:<br>
    <input  type="text"  name="table">

它通过 PHP 传递:

if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];
  
}

第一个动作正在进行中,并创建成功:Geoserver postgis 表是通过 PHP curl 创建的(下面有完整代码)

然后 javascript 尝试使用 PHP 插入获取 $table; 这将帮助它将新创建的 postgis Geoserver 表从 PHP 加载到 WFST javascript 中;

    <?php
echo "var thedata = " .$table. ";\n";
?>

...

  var wfstPoly = new L.WFST({
    url: 'https://mappingforyou.eu/geoserver/ows',
    typeNS: 'opendata',
    typeName: thedata,

但是这段代码不起作用:

    <?php
echo "var thedata = " .$table. ";\n";
?>

-- 除了 thedata javascript 变量外,代码工作正常。 整个表格:

<!DOCTYPE  html>
<html>
    <body>
    
        <h2>PG GS input test</h2>

        <form  method="POST"  action="test1.php">
            User:<br>
            <input  type="text"  name="user">
            <br>
            Password:<br>
            <input  type="password"  name="password">
          <br>
            New tablename:<br>
            <input  type="text"  name="table">
      
        <input type="radio" name="geom" id="Point" value="Point" />
<label for="Point">Point</label>

<input type="radio" name="geom" id="MultiLineString" value="MultiLineString" />
<label for="MultiLine">Line</label>

           <input type="radio" name="geom" id="MultiPolygon" value="MultiPolygon" />
<label for="MultiPolygon">Area</label>

                <br><br>
            <input  type="submit"  name="submit">

    </form>
    </body>
</html>

进入这个 javascript test1.php 页面:

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.css"/>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"/>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.toolbar.js/0.3.0/leaflet.toolbar.css" />
  <style>
    html, body, #map {
      margin: 0;
      height: 100%;
      width: 100%;
    }
  </style>
  <title>Leaflet-WFST polygon demo</title>
</head>
<body>
<div id="map"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.js"></script>
<link rel="stylesheet" href="https://mappingforyou.eu/javascript/leaflet.draw.css" /> 
<script src="https://mappingforyou.eu/javascript/leaflet.draw-src.js"></script>
<link type="text/css" rel="stylesheet" href="https://mappingforyou.eu/javascript/leaflet-easybutton.css" />
<script type="text/javascript" src="https://mappingforyou.eu/javascript/leaflet-easybutton.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4leaflet/1.0.2/proj4leaflet.js"></script>
<script src="https://mappingforyou.eu/javascript/leaflet-wfst.src.js"></script>


<script>

function jsFunction(){

    <?php
echo "var thedata = " .$table. ";\n";
?>

  var map = L.map('map', {editable: true}).setView([48.5, 2], 10);
  // add an OpenStreetMap tile layer
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

  var wfstPoly = new L.WFST({
    url: 'http://localhost:8080/geoserver/ows',
    typeNS: 'workspace',
    typeName: thedata,
    crs: L.CRS.EPSG4326,
    geometryField: 'geom',
    style: {
      color: 'blue',
      weight: 2
    }
  }).addTo(map)
    .once('load', function () {
      map.fitBounds(wfstPoly);
    });

    ////// draw and edit

    var drawControl = new L.Control.Draw({
    draw:{circle:false, circlemarker:false, rectangle:false,
          },
    edit:{featureGroup: wfstPoly } });
map.addControl(drawControl);

map.on('draw:created', function (e) {
    var layer = e.layer;
    wfstPoly.addLayer(layer)});

map.on('draw:edited', function (e) {
    var layers = e.layers;
    layers.eachLayer( function (layer) {
        wfstPoly.editLayer(layer);
        })

        });

    // Save button
L.easyButton('fa-save', function () {
         wfstPoly.save();
     }, 'Save changes').addTo(map);

}

</script>

<?php
    // Open log file
    $logfh = fopen("GeoserverPHP.log", 'w') or die("can't open log file");

    // Initiate cURL session
    $service = "http://localhost:8080/geoserver/rest"; // replace with your URL
    $ws = "workspace";
    $ds = "database";
    $request = "/workspaces/" . $ws . "/datastores/" . $ds . "/featuretypes";
    $url = $service . $request;
    $ch = curl_init($url);

if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];
  
}

define("GEOSERVER_REST_HOST", "http://localhost:8080/geoserver/rest");
define("GEOSERVER_USER", "admin:password");


    // Optional settings for debugging
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //option to return string
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_STDERR, $logfh); // logs curl messages

    //Required POST request settings
    curl_setopt($ch, CURLOPT_POST, True);
    //$passwordStr = "admin:geoserver"; // replace with your username:password
    curl_setopt($ch, CURLOPT_USERPWD, GEOSERVER_USER);

    //POST data
    curl_setopt($ch, CURLOPT_HTTPHEADER,
              array("Content-type: text/xml"));
    $xmlStr = "<featureType>";
    $xmlStr .= "<name>".$table."</name>";
    $xmlStr .= "<nativeName>".$table."</nativeName>";
    $xmlStr .= "<title>".$table."</title>";
    $xmlStr .= "<srs>EPSG:4326</srs>";
    $xmlStr .= "<attributes>";
    $xmlStr .= "<attribute>";
    $xmlStr .= "<name>geom</name>";
    $xmlStr .= "<binding>com.vividsolutions.jts.geom.".$geometry."</binding>";
    $xmlStr .= "</attribute>";
    $xmlStr .= "<attribute>";
    $xmlStr .= "<name>description</name>";
    $xmlStr .= "<binding>java.lang.String</binding>";
    $xmlStr .= "</attribute>";
    $xmlStr .= "<attribute>";
    $xmlStr .= "<name>timestamp</name>";
    $xmlStr .= "<binding>java.util.Date</binding>";
    $xmlStr .= "</attribute>";
    $xmlStr .= "</attributes>";
    $xmlStr .= "</featureType>";
    
   
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlStr);

    //POST return code
    $successCode = 201;

    $buffer = curl_exec($ch); // Execute the curl request

    // Check for errors and process results
    $info = curl_getinfo($ch);
    if ($info['http_code'] != $successCode) {
      $msgStr = "# Unsuccessful cURL request to ";
      $msgStr .= $url." [". $info['http_code']. "]\n";
      fwrite($logfh, $msgStr);
    } else {
      $msgStr = "# Successful cURL request to ".$url."\n";
      fwrite($logfh, $msgStr);
    }
    fwrite($logfh, $buffer."\n");

    curl_close($ch); // free resources if curl handle will not be reused
    fclose($logfh);  // close logfile
    
    echo '<script type="text/javascript">jsFunction();</script>';

    

        return $success;

?>


</body>
</html>

在您提供的代码中,这是:

if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];
  
}

...此之后:

echo "var thedata = " .$table. ";\n";

PHP 变量$table的初始赋值需要在使用之前到来。

如果表格文本输入提供的表名是一个字符串,则$table在分配给 Javascript 变量thedata时需要引用:


例如:

function jsFunction(){

<?php

if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];
  
}

// ...

echo "var thedata = \"" .$table. "\";\n";

?>

<!-- ... -->

请记住,PHP 在服务器上执行,包含 HTML、Javascript、CSS 的结果文本通过 HTTP 发送到浏览器。浏览器永远不会获得 PHP 代码。 浏览器仅获取 HTML、Javascript 和 CSS。一旦浏览器从服务器获取这些,它就会评估 Javascript 并呈现 HTML 和 CSS。

这个,在服务器上:

function jsFunction(){

<?php

if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];

}

// ...

echo "var thedata = \"" .$table. "\";\n";

?>

<!-- ... -->

...执行结果如下:

function jsFunction(){

var thedata = "user provided table name";


<!-- ... -->

...然后将其作为文本发送到浏览器。

我在这里进一步阐述了不同的 PHP 和 Javascript 执行上下文: https://stackoverflow.com/a/72023066/2743458

试试下面

var thedata = <?php echo $table; ?> <?php echo $table; ?> +"\n";

暂无
暂无

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

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