setInterval()在codeigniter中不起作用

时间:2017-07-04 04:18:11

标签: javascript php html ajax codeigniter-3

setInterval()函数在corePHP上运行良好,但该函数在codeigniter中没有响应。我想从另一个控制器获取数据而无需重新加载页面

控制器

home.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller{    
    public function index(){   
         $this->load->view('home_view');    
    }
}
?>

new1.php

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class New1 extends CI_Controller{
        public function index(){
            echo time()."-Time";
        }
    }
?>

home_view.php

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
  function sendMail(){
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET","<?php echo site_url('new1/'); ?>",false);
    xmlhttp.send(null);
    document.getElementById("getdata").innerHTML=xmlhttp.responseText;
  }
  sendMail();
 setInterval(function(){ sendMail(); },2000);
   </script>
</head>
<body>
<div id="getdata"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的错误是您正在重定向到视图文件。你必须创建一个控制器和功能

home.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller{    
    public function index(){   
         $this->load->view('home_view');    
    }
}
?>

home_view.php

<body>

        <div id="getdata"></div>
        <script>
            function sendMail() {
                 xmlhttp = new XMLHttpRequest();
                 xmlhttp.open("GET","<?php echo site_url('Ajax/sendmail'); ?>",false);
                 xmlhttp.send(null);
//                 console.log(xmlhttp.responseText);
//                document.getElementById("getdata").innerHTML = Date();
                document.getElementById("getdata").innerHTML = xmlhttp.responseText;
            }
            //sendMail();
            setInterval(function () {
                sendMail();
            }, 2000);
        </script>
    </body>

Ajax.php(控制器页面)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ajax extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function sendmail()
    {
//      $this->load->view('y');
            echo  'testing';
    }
}

此外,您还必须在配置文件中设置base_url。 config-&GT; config.php中 将$ config [&#39; base_ulr&#39;]设置为类似的东西

$config['base_url'] = 'http://localhost/test/';