gpt4 book ai didi

javascript - 使用 XMLHttpRequest 将记录添加到数据库

转载 作者:行者123 更新时间:2023-11-28 07:38:24 27 4
gpt4 key购买 nike

我有以下表格:

            <form id="form" name="form">
<img id="close" src="images/3.png" onclick ="div_hide()">
<h2>Grade</h2>
<hr>
<input id="fn" name="fn" placeholder="Faculty number" type="number">
<select id="grade_type" name="grade_type">
<option value="test" selected="selected">Тест</option>
<option value="attendance">Attendance</option>
<option value="homework">Homework</option>
</select>
<input id="grade" name="grade" placeholder="Points" type="number">
<a href="javascript:%20check_empty()" id="submit">Add record</a>
</form>

当我单击提交按钮时,我想将分数和 Grade_type 添加到数据库中。因此我使用 JavaScript 和 PHP:

// Validating Empty Field
function check_empty() {
if (document.getElementById('grade').value == "") {
alert("Fill the fields!");
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
alert("xmlhttpreq");
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var grade = String(document.getElementById('grade').value);
var grade_type = document.getElementById('grade_type');
var grade_type_value = String(grade_type.options[grade_type.selectedIndex].value);
var fn = String(document.getElementById('fn').value);
xmlhttp.open("GET","getuser.php?grade="+grade+"grade_type="+grade_type_value+"fn="+fn,true);
xmlhttp.send();
document.getElementById('form').submit();
}
}

getuser.php 文件的内容是:

<?php
require "config.php";

$fn = $_GET["fn"];
$grade = $_GET["grade"];
$type = $_GET["grade_type"];

echo "<script type='text/javascript'>alert('$fn');</script>";

try {
$conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $e) {
die("Database connection could not be established.");
}


$sql = $conn->prepare("SELECT * FROM students WHERE fn = ?");
$sql->execute(array($fn));
if($sql->rowCount() > 0) {
$statement = $conn->prepare("INSERT INTO points (student_fn, type, grade, datetime)
VALUES (?, ?, ?, CURRENT_TIMESTAMP)");
$statement->execute(array($fn, $type, $grade));
}
else {
echo "<script type='text/javascript'>alert('No such fn');</script>";
}
$conn = null;
?>

但是我认为它永远不会被执行,因为我从未看到警报的结果。我以前从未使用过 XMLHttpRequest,所以我什至不知道我的代码是否有效。我将非常感谢任何帮助。

最佳答案

您可以使用 jquery 来完成此操作。

$('#submit').click(function(){
$.ajax({
url: 'getuser.php',
type: 'GET',
data: $('#form1').serialize(),
success: function(result){
alert("Your data has been uploaded");
}

});

});

确保您需要将 jquery 文件添加到您的网站

关于javascript - 使用 XMLHttpRequest 将记录添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28327247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com