我一直在嘗試通過 CodeIgniter Controller 將數(shù)據(jù)插入數(shù)據(jù)庫。我已經(jīng)進(jìn)行了驗證過程并通過 ajax 響應(yīng)接收驗證錯誤。但似乎在表單中所有字段都已填寫,之后如果我單擊任何輸入字段,甚至無需單擊表單中的“保存”或“提交”按鈕,就會插入數(shù)據(jù)。因此,如果我按“名稱”字段、“顏色”字段或“價格”字段,則會插入數(shù)據(jù),而無需按“保存汽車”按鈕。**我的控制器:CarModel.php **<?phpclass CarModel extends CI_Controller{ public function index() { $this->load->view('car_model/list.php'); } public function showCreateForm() { $html = $this->load->view('car_model/create', '', true); $response['html'] = $html; echo json_encode($response); } public function saveModel() { $this->load->model('Car_model'); $this->load->library('form_validation'); $this->form_validation->set_rules('name', 'Name', 'required'); $this->form_validation->set_rules('color', 'Color', 'required'); $this->form_validation->set_rules('price', 'Price', 'required'); if ($this->form_validation->run() == true) { //save enteries to DB $formArray = array(); $formArray['name'] = $this->input->post('name'); $formArray['color'] = $this->input->post('color'); $formArray['transmission'] = $this->input->post('transmission'); $formArray['price'] = $this->input->post('price'); $formArray['created_at'] = date('Y-m-d H:i:s'); $this->Car_model->create($formArray); $response['status'] = 1; } else { $response['status'] = 0; $response['name'] = strip_tags(form_error('name')); $response['color'] = strip_tags(form_error('color')); $response['price'] = strip_tags(form_error('price')); } echo json_encode($response); }}我的模型:Car_model.php<?phpclass Car_model extends CI_Model { public function create($formArray){ $this->db->insert('car_models',$formArray); }}
2 回答
當(dāng)年話下
TA貢獻(xiàn)1890條經(jīng)驗 獲得超9個贊
我已經(jīng)找到問題了。發(fā)生問題是因為我將整個表單設(shè)置為插入操作的事件偵聽器。我需要使用submit而不是click在行中$("body").on("click", "#createCarModel", function(e) {。所以,我把它改成了$("body").on("submit", "#createCarModel", function(e) {。然后問題就不再發(fā)生了。
感謝所有試圖幫助我的人。
- 2 回答
- 0 關(guān)注
- 241 瀏覽
添加回答
舉報
0/150
提交
取消
