我有一张表格,
<form>
<input id="amount" type="text" placeholder="Give amount" name="myamount"/>
<button class="btn btn-lg" type="submit" id="btn1" >FirstBTN</button>
<button class="btn btn-lg" type="submit" id="btn2">SecondBTN</button>
</form>它需要将数据发送到控制器内部的函数。我正在尝试制作两个按钮,将数据发送到两个不同的控制器函数。这是我用html文件(View)编写的jquery代码:
<script type="text/javascript">
$('#btn1').click(function() {
$.ajax({
url: 'helloworld/firstmoney',
type: 'POST',
data: {'submit' : true ,myamount: $("#amount").val()},
success: function (result) {
}
});
});
</script>
<script type="text/javascript">
$('#btn2').click(function() {
$.ajax({
url: 'helloworld/secondmoney',
type: 'POST',
data: {'submit' : true ,myamount: $("#amount").val()},
success: function (result) {
}
});
});
</script>这是控制器,但我没有在控制器中获得任何值。
public function firstmoney(){
$this->load->helper('form');
$Money = $this->input->post("myamount");
$data = array(
'Money' => $Money
);
$this->load->view("page1", $data);
}
public function secondmoney(){
$this->load->helper('form');
$Money = $this->input->post("myamount");
$data = array(
'Money' => $Money
);
$this->load->view("page2", $data);
}我的控制器名是helloworld,我需要在$money中赋值,但是我不能让它工作。我是一个初学者程序员,所以请告诉我,我应该遵循的步骤。
发布于 2016-01-15 05:12:15
首先,您的AJAX应该如下所示。
$('#btn2').click(function() {
$.ajax({
url: 'helloworld/secondmoney',
method: 'POST',//not type
data: { myamount: $("#amount").val() }//no need for submit variable (although you can use it) since this will be submitted on click; no quotes over variables
})
.done(function(result)) {
//do your stuff on response
});
});第二:不需要ajax,你应该使用经典的表单和post方法,因为你是在数据被发送到的控制器/方法中进行重定向。AJAX需要JSON格式的响应,但本例并非如此。因此,是否将视图更改为具有具有方法和操作表单,是否更改控制器/方法以将JSON字符串返回给AJAX。
发布于 2016-01-17 17:09:00
var base_url= '<?php echo base_url() ?>';
url: base_url+'helloworld /firstmoney',发布于 2016-10-06 19:38:11
您可以尝试另一种方法来实现这一点
尝试下面的代码
表格
<form action="" method="post" id="myform">
<input id="amount" type="text" placeholder="Give amount" name="myamount"/>
<button class="btn btn-lg" type="submit" id="btn1" >FirstBTN</button>
<button class="btn btn-lg" type="submit" id="btn2">SecondBTN</button>
</form>然后,您可以添加jquery来更改单击submit按钮时的表单操作,如下所示
<script type="text/javascript">
$('#btn1').click(function() {
$('#myform').attr('action', 'Your domain/Your controller/firstmoney');
});
$('#btn2').click(function() {
$('#myform').attr('action', 'Your domain/Your controller/secondmoney');
});
</script>现在,如果您单击#btn1,窗体将调用firstmoney(),如果您调用#btn2,它将调用secondmoney()
并且您可以使用以下命令获取表单数据
$this->input->post('myamount');https://stackoverflow.com/questions/34797404
复制相似问题