dssu33392 2016-06-26 23:47
浏览 50
已采纳

如何使用Ajax在按钮单击时将值发布到控制器功能并同时重定向到新页面?

I have a button Next that changes the page -

<a class="disabled" href="step">
   <button class="btn btn-primary launch-btn disabled next">NEXT</button>
</a>

Also, when this button is clicked, I have an Ajax function that sends data to a controller function -

<script type="text/javascript">
$(function(){
    $('.next').click(function() {
    var a = $('#box').data('val');

    $.ajax({
       type: "POST",
       url: "<?php echo base_url(); ?>study/CreateData",
       data: a,
       success: function(data)
       {
          console.log(data); 
       },
       error: function()
       {
          console.log("fail");
       } 
     });
  });
});
</script>

And I'm using this to receive the value from Ajax -

public function CreateData() {
        $data = $this->input->post('data');
        return $data;
    }

When the Next button hits its controller where it changes to a new page, I'm trying to retrieve the value posted by Ajax to the CreateData() function -

public function step()
    {
        $data = $this->CreateData();
        if(!empty($data)){
            print_r($data); exit;
        }
        else {
            echo "blank"; exit;
        }
        $this->load->view('step2');
    }

However, this keeps echoing blank. This obviously means that the $data being returned is empty but I'm not sure why. The success function in my Ajax script is logging data, so it's posting the value to CreateData(). What am I doing wrong here?

  • 写回答

2条回答 默认 最新

  • doushadu0901 2016-06-27 01:25
    关注

    Your javascript should be something like this

    <script type="text/javascript">
    $(function(){
        $('.next').click(function() {
        var a = $('#box').data('val');
    
        $.ajax({
           type: "POST",
           url: "<?php echo base_url(); ?>study/CreateData",
           data: {my_data: a},
           success: function(data)
           {
              console.log(data); 
           },
           error: function()
           {
              console.log("fail");
           } 
         });
      });
    });
    </script>
    

    Notice the data property. I have changed it to an object containing the variable a.

    Now you should be able to retrieve this in your php function using

    public function CreateData() {
            $data = $this->input->post('my_data');
            return $data;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器