当我按下表单的“提交”按钮时,它会运行一个php文件,该文件存储数据库的答案。是否可以使用表单的“提交”按钮提交用户的选择,并在运行功能后立即提供用户的进一步操作?例如,在下面的简单形式和php中,如何在用户按提交时运行函数?
<form action="db.php" method="post">
A:<input type="radio" name="answer" value="A">
B:<input type="radio" name="answer" value="B">
<input type="submit" name="submit value="submit">
<?php
$con = mysqli_connect('localhost','my user id','my password');
if(!con)
{ echo 'not connected to server';}else { echo 'something else is wrong' ;}
if(!mysqli_select_db($con,'my user id')
{ echo 'Database error selection';}
if (isset($_POST['submit'])) {
$answer=$_POST['answer'];
$sql = INSERT INTO test1 (columnName) VALUES ('$answer');
mysqli_query($con,$sql); // Execute query
}?>
作为示例,让我们采用以下函数,该函数是较大文件的一部分。
function next() {
var qElems = document.querySelectorAll('#questions>div');
for (var i = 0; i < qElems.length; i++) {
if (qElems[i].style.display != 'none') {
qElems[i].style.display = 'none';
if (i == qElems.length - 1) {
qElems[0].style.display = 'block';
} else {
qElems[i + 1].style.display = 'block';
}
break;
}
}
}
答案 0 :(得分:0)
您可以向表单
添加onsubmit事件处理程序<form action="db.php" method="post" onsubmit="functionToCall()">
将在提交表单时调用给定的函数。如果要停止提交表单,请从函数返回false。正如@JokerDan所说,您也可以在函数中使用AJAX并完全省略表单操作。
function functionToCall()
{
//Do something before you submit your form (save data locally or whatever)
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200)
{
//Do something after submitting the form (if you want to change the page or redirect)
}
};
http.open('POST', 'db.php');
http.send(/*send post data here*/);
}
如果您想使用AJAX请求发送数据,则必须从表单中提取数据并将其放入http.send()行,其格式与您在URL中传递数据的格式相同(data = answer&amp; submit =真)