【发布时间】:2018-02-12 13:37:31
【问题描述】:
我会尽力解释这一点。当我通过 ajax 提交数据时,我在 action.php 中的变量始终为空,顺便说一句我正在尝试使用模态编辑我的数据。我只是不知道我哪里错了,希望你们明白我的意思。 这是我的代码...
//html表单
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title" id="exampleModalLongTitle">Edit Fields</h2>
</div>
<div class="modal-body">
<form id="form_data">
<form id="edit_data">
<input type="text" name="id" id="id2">
<input type="text" name="username" id="username2" class="form-control"><br>
<input type="text" name="subject" id="subject2" class="form-control"><br>
<input type="text" name="plan" id="plan2" class="form-control"><br>
<input type="submit" name="go_edit" value="Edit" id="edit2" class="btn btn-warning">
</form>
</form>
</div>
</div>
</div>
</div>
//这里是ajax脚本
$('#edit2').on('click', function(event){
event.preventDefault();
var edit = $("#edit_data").serialize() + "&go_edit=1";
$.ajax({
url:"action.php",
method:"POST",
data:edit,
success:function(data2){
alert(data2);
$('#exampleModalLong').modal('hide');
$('#list').load(window.loccation = ' #list');
}
});
});
});
// 用于编辑位于 action.php 中的表单的数据的 php 代码
if(isset($_POST['go_edit'])){
$id = $_POST['id'];
$username = $_POST['username'];
$subject = $_POST['subject'];
$plan = $_POST['plan'];
var_dump($where = array("id" => $id));
var_dump($myArray = array("username" => $username,
"subject" => $subject,
"plan" => $plan));
if($data->EditData("new_users",$myArray,$where)){
echo "Data Edited Successfully";
}
}
// 这是我在 action.php 中编辑的 sql
public function EditData($table,$fields,$where){
$sql = "";
$condition = "";
foreach ($where as $key => $value) {
$condition .= $key ."='". $value. "' AND ";
}
$condition = substr($condition, 0, -5);
foreach ($fields as $key => $value) {
$sql .= $key . "='".$value."', ";
}
$sql = substr($sql, 0, -2);
$sql = "UPDATE ".$table." SET ".$sql." WHERE ".$condition;
$query = mysqli_query($this->con,$sql);
if($query){
return true;
}
}
【问题讨论】:
-
为什么有嵌套表单?
-
此代码易受 SQL 注入攻击!不要那样做
-
if($data->EditData("new_users",$myArray,$where)){- $data 未定义 -
尝试通过console.log($("#edit_data").serialize())在浏览器控制台打印$("#edit_data").serialize()的输出。
-
@rollstuhlfahrer 这只是一种练习,我不打算主持这个。无论如何,谢谢你的提醒。