我有一个表格:
<form method="post" action="insert.php">
<input type="text" name="firstname" placeholder="Vorname" required>
<br>
<input type="text" name="lastname" placeholder="Nachname" required>
<br>
<input type="text" name="nickname" placeholder="Spitzname" required>
<br>
<input type="email" name="email" placeholder="Email" required>
<br>
<input type="submit" value="Speichern">
</form>
如您所见,我的操作是 action="insert.php"
,因此调用了我的 insert.php。将创建一个新网址并在浏览器中打开它。
但是如果我不想要那个怎么办?我想留在表单所在的同一个网站上,并且我不想直接调用任何 php。我更喜欢调用 JavaScript 函数。例如,我使用 ajax 进行选择:
function getData() {
$.ajax({
url: "queries.php",
data: {action: "retrieve_data"},
dataType: "json",
type: "post",
success: function(output) {
// do stuff
}
});
}
我也可以用插入物做类似的事情吗?
最佳答案
<html>
<body>
<form method="post" action="insert.php" id="insertForm">
<input type="text" name="firstname" placeholder="Vorname" required>
<br>
<input type="text" name="lastname" placeholder="Nachname" required>
<br>
<input type="text" name="nickname" placeholder="Spitzname" required>
<br>
<input type="email" name="email" placeholder="Email" required>
<br>
<input type="button" id="insertData" value="Speichern">
</form>
<script type="text/javascript" src="lib/js/jquery-2-1-3.min.js"></script>
<script type="text/javascript">
$(function () {
$('#insertData').click({ inputs:$('#insertForm :input') }, getData);
});
function getData(o) {
var values = {};
o.data.inputs.each(function() {
values[this.name] = $(this).val();
});
$.ajax({
url: "queries.php",
data: {action: "retrieve_data", firstname: values['firstname'], lastname: values['lastname'], nickname: values['nickname'], email: values['email']},
dataType: "json",
type: "post",
success: function(output) {
// do stuff
}
});
}
</script>
</body>
</html>
在这里,您可以随时编辑您想要的内容,或者哪些值是可选的等等。
请记住,我使用了 type="button",因此页面不会重新加载,因此操作可能会保持为空。
关于javascript - 在 HTML 中不调用 PHP 文件的情况下将数据插入 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31208211/