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 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题