我正在尝试使用javascript和php的组合来在提交表单时更新sql数据库中的列。sql 数据库的名称是"answerswers",数据库中的列的名称是"FunctionsConsistency",表单的 id 是"easytohard"。但是,我不确定是否可以在此 JavaScript 代码中包含 php(下面用星号注明)。
<script type='text/javascript'>
$(document).ready(function () {
$('#easytohard').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
******THIS IS THE PHP CODE*********
$stmt = $db->prepare("UPDATE answers SET FunctionsConsistency = 1
WHERE id = ? AND FunctionsConsistency = 0") or die($db->error);
$stmt->bind_param("i", $id);
$stmt->execute();
******************
},
});
});
});
</script>
谢谢!
你不能
像这样混合Javascript和PHP。
Php应该在服务器端执行,而javascript应该在客户端执行。
你可以把 Php 文件放在你的服务器上,然后使用 ajax 或其他任何东西向它发送请求。
像这样:
<script type='text/javascript'>
$(document).ready(function () {
$('#easytohard').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $('http://path/to/your/php/file/on/server'),
type: "POST",
data: {id: 'your desired id here'},
success: function (data) {
// if it reach this line, it means script on the php file is executed
},
});
});
});
</script>
并且您的php文件应该在您的服务器上(路径:http://path/to/your/php/file/on/server
),包含适当的include
才能工作。
<?php
$stmt = $db->prepare("UPDATE answers SET FunctionsConsistency = 1
WHERE id = ? AND FunctionsConsistency = 0") or die($db->error);
$stmt->bind_param("i", $_POST['id']);
$stmt->execute();
请注意,您可以使用 php 中的 $_POST
访问 post 参数。
您仍然应该考虑一些事情,例如,当请求没有到达服务器时,或者如果服务器无法执行php文件......,但是您知道了。
另外,看看这个和这个。希望这有帮助。