使用jquery Ajax获取控制器的输入值

时间:2016-01-14 20:30:04

标签: jquery ajax codeigniter controller

这是表格

<form>
    <input id="amount"  type="text" placeholder="Amount in &euro;"  name="writtenamount"/>
    <button class="btn btn-lg" type="submit" id="btn1" >BTN1</button> 
    <button class="btn btn-lg" type="submit" id="btn2">BTN2</button>
</form>

其中有一个输入字段,我需要做的就是使用jquery ajax将值推送到控制器。但我想它写错了。

<script type="text/javascript">
$('#btn1').click(function() { 
   $.ajax({
     url: 'moneyexchange/invest_first_page',
     type: 'POST',
     data: { 
        writtenamount: $("#amount").val()
     },
     success: function (result) {
        alert(result);
     }
  });  

});

</script>

我在这里有一个控制器,

 public function invest_first_page(){
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->view('header');
        $userProvidedAmount = $this->input->post("writtenamount");
        $data =  array(
        'userProvidedAmount' => $userProvidedAmount
         );
        $this->load->view("firstPage", $data);
        $this->load->view('footer');
}

现在我无法将输入的值发送到控制器,所以需要帮助解决这个问题。

3 个答案:

答案 0 :(得分:0)

您需要检查$userProvidedAmount是否具有可用值。

$userProvidedAmount = $this->input->post("writtenamount");
if(!empty($userProvidedAmount))
{
   $data['provided_amount'] = $userProvidedAmount;
   $this->load->view("firstPage", $data);
   $this->load->view('footer');
}
else
{
   //load (or reload) the form with a prompt about the amount being required
}

您确实需要了解如何使用form validation

在第一页&#39;查看访问这样的数据。

<div>You entered <?= $provided_amount; ?>. Thanks for your support!</div>

答案 1 :(得分:0)

实际上一切都很好,只需将旧代码更改为

即可
method: 'POST',
data: { writtenamount: $("#amount").data('value')},

答案 2 :(得分:0)

不确定,但在我看来,当你点击提交按钮时,你有两件事情在进行。

1)您正在调用jQuery ajax方法,该方法将发送ajax请求并提醒响应。
2)表格以正常(非ajax)方式提交。这是因为您没有停止提交按钮的默认行为,因此页面将重新加载。

所以,你可以添加一个preventDefault();到你的jQuery单击处理程序方法(确保将事件参数添加到此处理程序):

$('#btn1').click(function( event ) { 
   $.ajax({
     url: 'moneyexchange/invest_first_page',
     type: 'POST',
     data: { 
        writtenamount: $("#amount").val()
     },
     success: function (result) {
        alert(result);
     }
  });  


  // stop default behavior of form submission
  event.preventDefault();

});

或者,由于这些并非真正提交按钮,因为您想使用非ajax方法提交表单,您可以将按钮的输入类型更改为“按钮”而不是“提交”:

<form>
    <input id="amount"  type="text" placeholder="Amount in &euro;"  name="writtenamount"/>
    <button class="btn btn-lg" type="button" id="btn1" >BTN1</button> 
    <button class="btn btn-lg" type="button" id="btn2">BTN2</button>
</form>

我认为其中任何一种方法都有效。我很想改变输入,因为在这里使用'submit'类型会产生误导 - 当你选择这些时,你真的不想提交。

我希望我能正确理解你的问题,并且我有所了解。