从jQuery调用Controller函数

I'm working on some codes. Here's my code

jQuery

duration = 30;
var countdown = setInterval(timer,1000);
var url = window.location.origin + '/pro/index.php/Test';

function timer(){
  duration = duration - 1; 
  if(duration<=0){
    clearInterval(countdown);
    window.location(url+'/next');
  }
}

I want to redirect and run function in Test/next. In next() method, it will rule where the link should go. url helper also has been added automatically in Loader

Controller

public $num;
public $val;

public function index(){
  // get the value from GET method
  $this->num = $this->input->get('num');
  $this->val = $this->input->get('val');
}

public function next(){
  $x = $this->num;
  $x = $x + 1;
  if($x < 4){
    redirect(site_url('index.php/Test?x='.$x/.'&num='.$this->num));
  }
  else{
    // it will redirect to another page
    // redirect(site_url('index.php/Home'));
    echo 'x = '.$x.', num = '.$this->num;
  }

(The codes above have been simplified).

The method has been run, but the url was localhost/pro/index.php/Test/next and echo-ing :

x = , num =

It seems like the global property doesn't work for the function called from JS/jQuery. Any explanation or solution for this?

douyi1899
douyi1899 它有效,谢谢
大约一年之前 回复
dtmu88600
dtmu88600 你可以添加一个构造函数并执行$this->num=$this->input->get('num');$this->val=$this->input->get('val');在那个功能里面。
大约一年之前 回复

2个回答

You can access controller function from view page to using base URL (Click here how to do it?). Then use jQuery Ajax call controller function.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$.ajax({
    type: 'post', url: '<?php echo base_url("next");?>',
    data: {},
    success: function(result){
        console.log(result);
    }
});

You need ajax calling. In your View file

<button class="call_ajax" name="submit">Call Ajax</button>
    <script type="text/javascript">
        $('.call_ajax').click(function(){
        var value1 = 'some data';
        var value2 = 'some data'; 
        $.ajax({
            url: '<?php echo site_url('your_controller/your_function'); ?>',
            type: 'POST',
            data: {
                key1: value1,
                key2: value2
            },
            dataType: 'json',
            success: function(url) {
            window.location.href = url;
         }
        });
    });</script>

in your Controller

your_function(){
    $data1 = $this->input->post('key1');
    $data2 = $this->input->post('key2');
    // do Data Processing
    // For return some data ; 
    echo "https://some-webiste-url/";

    // FOR Array

    echo json_encode($any_data_array);

}

NOTE : controller Function called from ajax will not do redirection . If you want to direct to some other url , you have to do that in the Javascript Section Using

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问