我正在尝试使用javascript和php的组合来在提交表单时更新sql数据库中的列。 sql数据库的名称是"答案,"数据库中列的名称是" 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>
谢谢!
答案 0 :(得分:3)
你不能像那样混合使用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
访问帖子参数。
还有一些事情你应该考虑,例如当请求没有到达服务器或服务器无法执行php文件时...,但你明白了。