如何在不清除表单的情况下将表单数据提交到单独的PHP文件

时间:2019-04-15 22:33:03

标签: php html

我正在尝试将表单数据提交到一个单独的PHP文件,但是表单对我一直关闭!

我尝试了POST和GET,并且尝试了action =“ ReadFrmData.php”,但没有“ act = form”。我的浏览器是Windows 10(PHP 7.1.26)上的Chrome。

这是表格:

<!DOCTYPE html>
<html>
<head>

</head>
<body>

        <form method="post" action="ReadFrmData.php?act=form" name="myform">
            Value:<input type="text" style = "width: 100px"name="sdata" value = "0"><br><br>
            Set Position High Limit<input type="radio" name="Set" value="SetPosHigh"><br>
            Set Position Low Limit<input type="radio" name="Set" value="SetPosLow"> <br>
            <input type="submit" name="sendset" value="Send"/><br>
        </form>


</body>
</html>

这是单独的PHP文件:

<?php
/* Read data and commands from the form */ 

include_once 'ChromePhp.php';

if (isset($_POST['sendset'])){  /* Command submit button */
    $sdata = $_POST['sdata'];
    $param = $_POST['Set'];
    $val = 0;   
    ChromePhp::log("Sendset");  //console message
}   
?>

我需要保持表格打开状态。 谢谢!

2 个答案:

答案 0 :(得分:1)

您的要求位于Frontend(HTML)文件中,而不是PHP。

使用Javascript捕获表单的值,然后如上所述通过Ajax发布它们。

参考:

https://stackoverflow.com/a/40758582/8004150

作为指导。这样,您还可以处理由PHP生成的响应。

答案 1 :(得分:1)

您正在寻找AJAX(异步JavaScript和XML)。简而言之,就是使用XMLHttpRequest对象与服务器进行通信。它可以发送和接收各种格式的信息,包括JSON,XML,HTML和文本文件。 AJAX最吸引人的特点是其“异步”特性,这意味着它可以与服务器通信,交换数据和更新页面,而无需刷新页面。

这是香草javascript实现之一的示例:

document.querySelector('form[name=myform]').onsubmit = ev => {
  ev.preventDefault();

  // Set up our HTTP request
  var xhr = new XMLHttpRequest();

  // Setup our listener to process completed requests
  xhr.onload = () => {

    // Process our return data
    if (xhr.status >= 200 && xhr.status < 300) {
      // What do when the request is successful
      console.log('success!', xhr);
    } else {
      // What do when the request fails
      console.log('The request failed!');
    }

    // Code that should run regardless of the request status
    console.log('This always runs...');
  };

  // Create and send a GET request
  // The first argument is the post type (GET, POST, PUT, DELETE, etc.)
  // The second argument is the endpoint URL
  xhr.open('POST', 'ReadFrmData.php?act=form');
  xhr.send();
}
<form method="post" name="myform">
  Value:<input type="text" style="width: 100px" name="sdata" value="0"><br><br> Set Position High Limit<input type="radio" name="Set" value="SetPosHigh"><br> Set Position Low Limit<input type="radio" name="Set" value="SetPosLow"> <br>
  <input type="submit" name="sendset" value="Send" /><br>
</form>

如果您已经在应用程序中使用jQuery,请查看jQuery.ajax(),因为它实现起来更简单(imo)。