dongtiao1817 2017-08-01 09:07 采纳率: 100%
浏览 32
已采纳

带有ajax和codeigniter的“错误请求”

Windows 10, Codeigniter 3, Wamp3.

Ajax post throws a Bad Request error. This is an old chestnut but online research shows the problem usually to be CSRF. However I emphasize at the outset that I have csrf disabled for this test:

config['csrf_protection'] = FALSE;

I have set up some deliberately very simple test code. The controller looks like this:

class Ajax extends CI_Controller {

public function index() {


$this->load->view('pages/index');
}

public function hello($name) {
    $fullname = $this->input->post('fullname');
    echo 'Hello '.$fullname;

}

}//EOF

and the view looks like this:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo Ajax</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
    $(function() {
        $('#bttHello').click(function(){
            var fullname = $('#fullname').val();
            $.ajax({
                type:'POST',
                data: {fullname: fullname},
                url:'<?php echo base_url('ajax/hello'); ?> + fullname',
                success: function(result) {
                    $('#result1').html(result);

                }
            });

        });

    });
</script>
</head>
<body>

Name <input type="text" id="fullname">
<input type="button" value="Hello" id="bttHello">
<br>
<span id="result1"></span>

</body>
</html>

The console shows a Bad Request

POST XHR http://localhost/faith/ajax/hello%20+%20fullname [HTTP/1.1 400 Bad Request 9ms]

So if csrf is not the culprit, is it a Wamp issue? Everything else seems to work fine. I have spent so much time on this! What is going on?

  • 写回答

5条回答 默认 最新

  • dongzouh51192 2017-08-01 09:21
    关注

    Data are already sent through POST. No need to pass it through URL

    <script>
    $(function() {
      $('#bttHello').click(function(){
        var fullname = $('#fullname').val();
        $.ajax({
          type:'POST',
          data: {fullname: fullname},
          url:"<?php echo base_url('ajax/hello'); ?>",
          success: function(result) {
            $('#result1').html(result);
          }
        });
      });
    });
    </script>
    

    And, remove parameter $name from controller action hello().

    public function hello() {
      $fullname = $this->input->post('fullname');
      echo 'Hello '.$fullname;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么