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条)

报告相同问题?

悬赏问题

  • ¥100 有偿求易语言word文档取doc和docx页数方法或模块
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低
  • ¥15 目标计数模型训练过程中的问题
  • ¥100 Acess连接SQL 数据库后 不能用中文筛选
  • ¥15 用友U9Cloud的webapi
  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验