首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将PHP变量从HTML表单传递到Javascript

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

Stack Overflow用户
提问于 2022-06-17 12:19:30
回答 2查看 163关注 0票数 -2

您能帮我把一个从html表单中提取的变量传递到javascript中吗?

表单请求表名。

代码语言:javascript
复制
  <br>
    New tablename:<br>
    <input  type="text"  name="table">

它通过PHP传递:

代码语言:javascript
复制
if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];
  
}

第一个操作正在进行,并成功地创建了: Geoserver postgis表是通过PHP创建的(下面的全部代码)

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

代码语言:javascript
复制
    <?php
echo "var thedata = " .$table. ";\n";
?>

..。

代码语言:javascript
复制
  var wfstPoly = new L.WFST({
    url: 'https://mappingforyou.eu/geoserver/ows',
    typeNS: 'opendata',
    typeName: thedata,

但是这个代码不起作用:

代码语言:javascript
复制
    <?php
echo "var thedata = " .$table. ";\n";
?>

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

代码语言: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>

进入这个javascripttest1.php页面:

代码语言:javascript
复制
<!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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-06-17 12:32:18

在您提供的代码中,如下所示:

代码语言:javascript
复制
if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];
  
}

...comes之后:

代码语言:javascript
复制
echo "var thedata = " .$table. ";\n";

PHP变量$table的初始赋值需要在使用它之前完成。

如果表单文本输入提供的表名是字符串,则当$table被分配给Javascript变量thedata时,需要引用它。

例如:

代码语言:javascript
复制
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。

这个,在服务器上:

代码语言:javascript
复制
function jsFunction(){

<?php

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

}

// ...

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

?>

<!-- ... -->

执行了...is,结果如下:

代码语言:javascript
复制
function jsFunction(){

var thedata = "user provided table name";


<!-- ... -->

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

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

票数 1
EN

Stack Overflow用户

发布于 2022-06-17 12:33:28

试着在下面

var thedata =<?php echo $table; ?>+“n”;

票数 -3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72659291

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档