【发布时间】:2016-07-20 17:08:39
【问题描述】:
在下面的函数中,我有两个发布请求。一种是在数据库中插入值(submit.php),另一种是根据businessid(edit.php)编辑数据库中的现有值。但是,该脚本仅执行第一部分。也就是说,当“keuze”选择并在提交时单击时,脚本很好地插入数据库。 But when something else than "keuze" is chosen and submit is clicked, the script does not edit the records in the database.我该怎么做才能解决这个问题?
submitformfunction: function(){
$(document).on('submit', '#form', function(){
var data = $(this).serialize();
var target = $('#busselect option:selected').val();
var businessid = $('#busselect').children(":selected").attr("id");
if(target == 'keuze'){
$.ajax({
type : 'POST',
url : 'submit.php',
data : data,
success : function(data)
{
alert('Company added');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
}
else
{
$.ajax({
type : 'POST',
url : 'edit.php',
data : businessid+data,
success : function(data)
{
alert('Company modified');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
}
});
},
提交.php:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST )
{
$naam = addslashes(htmlentities($_POST['uitgevoerd_door_naam']));
$mysqli->query("INSERT INTO form (uitgevoerd_door_naam)
VALUES ('$naam')");
}
mysqli_close($mysqli);
?>
edit.php:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST )
{
$naam = addslashes(htmlentities($_POST['uitgevoerd_door_naam']));
$mysqli->query("UPDATE form SET uitgevoerd_door_naam='$naam' WHERE id='$_POST[business_id]'");
}
mysqli_close($mysqli);
?>
【问题讨论】:
-
你说过“不更新”。
edit.php文件是否会触发?您是否使用浏览器的开发人员“网络”选项卡进行故障排除? AJAX 调用会出去吗? -
您很容易受到sql injection attaacks 的攻击,并且您的edit ajax 调用失败,因为您传入了
test+businessid。test似乎不存在于您的代码中,并且会生成一个 PHP 无法识别为key=value表单提交的数字/字符串,从而将 $_POST 留空。 -
仅供参考,很好地格式化了你的代码——它看起来很不错!您可能会考虑三件事:双换行符只是创建开放空间,所以删除双换行符 - 使您的
if() {格式一致 - 在某些地方它在同一行,在某些地方{在单独一行 - 最后,不要在 PHP 文件的末尾使用?>。现在认为最好的做法是省略 php 文件末尾的那些。 -
只是为了确认一下,您在 if 循环之前尝试过
alert(target);吗?当您选择'keuze'以外的选项时会发生什么? -
亲爱的 Shrikant,是的,我试过了,它产生了正确的值。此外,@cale_b tnx 提到了网络选项卡。 ajax 调用确实会输出到 edit.php。