我正在尝试使用ajax从对话框内的表单中插入一行到我的repair_history表中。
以下是打开对话框的函数,其形式为:
<script>
$(function() {
$( "#repair-dialog" ).dialog({
autoOpen: false,
height: 300,
width: 450,
modal: true,
buttons: {
"Save": function() {
insert(
$( "#repair-dialog-date" ).val(),
$( "#repair-dialog-id" ).val(),
$( "#repair-dialog-comment" ).val(),
$( "#repair-dialog-save_type" ).val()
);
$( this ).dialog( "close" );
setTimeout(function(){location.reload(true);},500);
},
"Cancel": function() {
$( this ).dialog( "close" );
}
},
close: function() {
}
});
$( "#record_repair" ).click(function() { $( "#repair-dialog" ).dialog( "open" ); });
});
function insert(date,id,comment,save_type) {
mydata = {
"date" : date ,
"id" : id ,
"comment" : comment ,
"camera_id" : "<?php= $products['camera_id']?>" };
$.ajax({
type: "POST",
url: "localhost/cibs/index.php/api/record_save/"+save_type,
data: {data:JSON.stringify(mydata)},
dataType: "json",
cache : false
});
}
这是api.php控制器中试图插入的函数:
function record_save()
{
$this->load->database();
$mydata = $this->input->post('data');
$date = $mydata['date'];
$comment = $mydata['comment'];
$id = $mydata['id'];
$camera_id = $mydata['camera_id'];
$table = "repair_history";
$data = array("camera_id" => $camera_id, "repair_id" => $id, "date" => $date, "comment" => $comment);
$this->db->insert($table,$data);
}
然后是对话框:
<div id="repair-dialog" title="Add New Repair" style="font-size: 15px;">
<form id="repair">
<input style="height:0px; top:-1000px; position:absolute" type="text" value="">
Repair id: <input type="text" id="repair-dialog-id" /><br>
Repair date: <input type="text" id="repair-dialog-date" /><br>
Comment: <input type="text" id="repair-dialog-comment" /><br>
<input type="hidden" value="repair" id="repair-dialog-save_type">
</form>
</div>
任何回复真的很感激!谢谢! :)
答案 0 :(得分:2)
您不需要对对象进行字符串化:
$.ajax({
type: "POST",
url: "http://localhost/cibs/index.php/api/record_save/"+save_type,
data: mydata,
dataType: "json",
cache : false
});
在php中:
function record_save()
{
$this->load->database();
$table = "repair_history";
$data = array(
"camera_id" => $this->input->post('camera_id'),
"repair_id" => $this->input->post('id'),
"date" => $this->input->post('date'),
"comment" => $this->input->post('comment')
);
$this->db->insert($table,$data);
}
答案 1 :(得分:1)
我不确定您的函数$this->input->post('data')
是如何工作的,但是您将数据作为json字符串发布,因此您应该确保首先对该数据进行json_decode。
替换
$mydata = $this->input->post('data');
通过
$mydata = json_decode($this->input->post('data'), true);