我尝试在Codeigniter中通过jQuery ajax()提交表单……但没有任何反应…… :(
对不起这个重复和重复的问题,但我真的不知道如何解决。
有一个按钮和两个text_input,当我点击这个按钮时,如果它正常工作,我会看到一个警报并向我显示“成功”,但不幸的是,我什么也看不见。
没有 !!
我不知道为什么:(
请帮助我,请……我在stackoverflow或其他网站上阅读了很多有关codeigniter的教程,但是我找不到任何可以解决我的问题,请教我们。
这是一个非常简单的表格
文件名:test.php
test <link rel="stylesheet" href=""> <link rel="stylesheet" href=""> <script src=""> <script src=""> <script src="">
我想通过jQuery Ajax()以这种forms提交数据,JS文件如下
文件名:practice.js
$(document).ready(function(){ $("#test_form").submit(function(e){ e.preventDefault(); var tdata= $("#test_form").serializeArray(); $.ajax({ type: "POST", url: "http://localhost/index.php/static_data/test_add", dataType: json, data: tdata, success:function(tdata) { alert('SUCCESS!!'); } }); }); });
以下是我的控制器
文件名:static_data
load->view('test'); } public function test_add() { $this->load->model("paper"); $this->paper->test_add(); } }
这个文件是我的模型集
文件名:paper.php
load->helper('form'); $this->load->helper('html'); $this->load->database(); $tdata = array( 'num' => $this->input->post('num'), 'name' => $this->input->post('name'), ); $this->db->insert('test_table',$tdata); } }
试试这个 – >在你的test.php
文件中,给出action属性
action="/static_data/test_add"
然后,在您的practice.js文件中:
$('#test_form').submit(function() { var tdata= $("#test_form").serializeArray(); var that = $(this), url = that.attr('action'), type = that.attr('method'), data = tdata;
现在,为了测试,在practice.js
中的success
函数中,只需编写以下内容:
success: function(response) { console.log(response); }
在这里,您得到的响应是您的控制器返回给您的,现在要测试它,只需键入echo "hello";
或任何东西,只是回应一些东西。 (这是因为你说教我:))
现在看看这是否有效,打开开发工具(如果你在谷歌浏览器中),转到控制台选项卡,然后从底部选择日志,如果一切正常,它将返回您在控制器中写入的回显消息。
此外,要查看表单是否正确提交,请选择网络选项卡,当您点击提交按钮时,网络选项卡将显示数据是否已正确提交。
试试这个,如果不起作用,请发表评论。
我想你可以通过下面给出的简单的ajax请求轻松解决这个问题:
$(document).ready(function(){ $("#test_form").on("submit", function(event){ event.preventDefault(); $.ajax({ url : base_url+"static_data/test_add", type : "post", data : $("#test_form").serialize(), dataType : "json", success(data) { alert('SUCCESS!!'); } }); }); });
在此之前,请在头文件的视图文件(test.php)中写下这个
试试这个 :
Practice.js
$(document).ready(function(){ $("#test_form").submit(function(e){ e.preventDefault(); var tdata= $("#test_form").serializeArray(); $.ajax({ type: "POST", url: 'http://localhost/[CodeIgniterDirectory]/index.php/static_data/test_add', data: tdata, success:function(tdata) { alert('SUCCESS!!'); }, error: function (XHR, status, response) { alert('fail'); } }); }); });