将HTML转换为php数组

Convert HTML to php array

本文关键字:php 数组 转换 HTML      更新时间:2023-09-26

我目前有一个表格里面。我想把这些值传递给php脚本。我最好的办法是什么?我查过的所有资料都不适用。

我的表单是这样设置的:

<form id="pageform" action="phpscript.php" method="post">
  <table>
    <tbody>
      <tr>
        <td><input type="text" class="nestedInput"name="txtName" value="John"></td><td><input type="text" class="nestedInput" name="txtLocation" value="North St"></td><td><input type="text" class="nestedInput" name="txtAge" value="42"></td>
      </tr>
      <tr>
        <td><input type="text" class="nestedInput"name="txtName" value="John"></td><td><input type="text" class="nestedInput" name="txtLocation" value="North St"></td><td><input type="text" class="nestedInput" name="txtAge" value="42"></td>
      </tr>
      <tr>
        <td><input type="text" class="nestedInput"name="txtName" value="John"></td><td><input type="text" class="nestedInput" name="txtLocation" value="North St"></td><td><input type="text" class="nestedInput" name="txtAge" value="42"></td>
      </tr>
    </tbody>
  </table>
  <input type="button" name="btnSubmit" id="btnSubmit" value="Submit">
</form>
jQuery:

$("#btnSubmit").click(function(){
  var array = [];
  $(".nestedInput").each(function(n){
    array[n] = $(this).val();
  });
  document.forms["pageform"].submit();
});

我的PHP:

<?php
  $array=json_decode($_POST['json']);
  print_r($array);    
?>

我想做的是使用每个tr中每个输入的值运行mysqli插入。关于我如何做到这一点的任何想法?

在phpscript.php中,您可以这样访问这些变量:

$name = $_GET['txtName']
$location = $_GET['txtLocation']
$age = $_GET['txtAge']

通过表单提交的变量将存储在全局数组$_GET或$_POST中(取决于您的表单是使用GET还是POST)。您的表单没有method属性来定义它,所以它默认为GET。

同样值得注意的是,你的提交按钮的id属性应该是id="btnSubmit",而不是id="#btnSubmit"

使用jQuery ajax方法;

function send_form(this) {
   jQuery.ajax({
      type: 'POST',
      url: $(this).attr('action'),
      data: $(this).serialize(),
      error:function(){ console.log('error'); },
      success: function(data) { $console.log(data);}
   });
   return false;
}

表单;

<form id="pageform" onsubmit="return send_form(this);" action="phpscript.php">
   <table>
      <tbody>
        <tr>
          <td><input type="text" class="nestedInput"name="txtName" value="John"></td>
        </tr>
        <tr>
          <td><input type="text" class="nestedInput" name="txtLocation" value="North St"></td>
       </tr>
       <tr>
         <td><input type="text" class="nestedInput" name="txtAge" value="42"></td>
      </tr>
   </tbody>
</table>

phpscript.php;

$name = $_POST['txtName'];
$txtLocation= $_POST['txtLocation'];
$txtAge= $_POST['txtAge'];

不需要jQuery和所有这些,只需使用HTML <form>标签的默认功能

首先,修改

<input type="button" name="btnSubmit" id="#btnSubmit" value="Submit">

<input type="submit" name="btnSubmit" id="#btnSubmit" value="Submit">

然后为你的表单标签添加一个方法,比如

<form id="pageform" action="phpscript.php" method="post">

现在,在您的phpscript.php页面中,将var_dump($_POST)添加到php标签的开始部分。

点击提交按钮后,var_dump()将打印一个数组,其中包含所有传递的表单数据。

要检索php页面中的值,您可以这样做

echo $_POST['txtName'];

其中txtName是输入的名称。

其他输入也是如此…