我必须创建一个创建按钮的表单,单击该图标会显示动态文本字段。
我的javascript就是:
function add() {
//Create an input type dynamically.
var element = document.createElement("input");
element.style.borderRadius ="5px";
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "ip2");
element.setAttribute("name", "ip2");
element.setAttribute("placeholder", "ip2");
element.setAttribute("required", "true");
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
我正在使用以下代码作为按钮和所需的容器:
<form method="post" action="insert.php">
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<span id="fooBar"></span>
</form>
输入字段很好。我只想知道如何从动态输入字段获取值并将其存储在db。
中提前致谢
答案 0 :(得分:0)
将fiels添加到fooBar后,它就在表单内。如果您通过提交按钮(请参阅下面的HTML代码)或通过javascript document.getElementById("myForm").submit();
提交表单,则必须使用服务器上的脚本处理发送到服务器的结果,例如:用PHP。
echo '<pre>';
print_r( $_POST ); /* Show ALL given $_POST input */
echo '</pre>';
error_reporting(0);
$conn = mysqli_connect("localhost","root","","pnb");
if( !$conn ) {
die('Could not connect to MySQL: ' . mysqli_error() );
}
if( isset( $_POST['ip2'] ) AND !empty( $_POST['ip2'] ) ) {
$ip2 = $_POST['ip2'];
mysqli_query( $conn, 'INSERT INTO records (ip) VALUES ("' . mysqli_real_escape_string( $conn, $ip2 ) . '")' );
echo 'Row added!';
}
mysqli_close( $conn );
HTML code:
<form method="post" action="insert.php">
<input type="button" value="Add" onclick="add()"/>
<input type="submit" value="submit" />
<span id="fooBar"></span>
</form>
<script type="text/javascript">
function add() {
//Create an input type dynamically.
var element = document.createElement("input");
element.style.borderRadius ="5px";
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "ip2");
element.setAttribute("name", "ip2");
element.setAttribute("placeholder", "ip2");
element.setAttribute("required", "true");
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</script>
注意: document.forms[0].element.value
不存在,因此我从上面的代码中删除了它。我还添加了一个提交按钮,将表单提交到服务器上的insert.php
脚本。
以上脚本将检查名称为&#34; ip2&#34;收到了。它将设置MySQLi连接到数据库并在表&#34; tablename&#34;中插入值。上述代码应放在insert.php
答案 1 :(得分:0)
PHP:
Model
HTML:
if(isset($_POST['foo'])) {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$item = $_POST['foo']
$sql = "INSERT INTO thetable (item)
VALUES ('$item')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
此外,如果您要定位外部文件,则应将表单上的<form action="" method="post">
<input type="text" name="foo" value="foo">
<input type="submit" value="Submit">
</form>
attr更新为文件的网址,例如action