How to put data from a controller into a specfic d

2019-05-31 22:37发布

问题:

How can I load data i.e $mytweets into a specific div within a specific template/view i.e footer.php?

I have twitteruserfeed.php as my Controller for getting the tweets, but I don't know how to present it within an already existing.

HTML:

<div id="fresh-tweetfeed"> $mytweets GOES HERE </div> 

PHP:

class TwitterUserFeed extends CI_Controller
{
    public function __construct()
    { 
        parent::__construct();    
    }

    public function getTweets()
    {
        $params = array(
            'userName' => 'RowlandBiznez',
            'consumerKey' => 'hgfhhgffhg',
            'consumerSecret' => 'hhffhfghfhf',
            'accessToken' => 'hfhhhfhhf',
            'accessTokenSecret' => 'hfhfhfhfhhfhfh',
            'tweetLimit' => 5 // the no of tweets to be displayed
        );
        $this->load->library('twitter', $params);
        $tweets = $this->twitter->getHomeTimeLine();
        $this->load->helper('tweet_helper');
        $mytweets = getTweetsHTML($tweets);

        echo $mytweets;
    }
}

I also have a helper file tweet_helper.php. Help me out with this presentation.

回答1:

Solution #1:

If the tweets must be displayed on every page, extend the CI_Controller (create MY_Controller.php file inside application/core folder) and fetch/store the tweets on a property:

class MY_Controller extends CI_Controller
{
    public $tweets = '';

    public function __construct()
    {
        // Execute CI_Controller Constructor
        parent::__construct();

        // Store the tweets
        $this->tweets = $this->getTweets();
    }

    public function getTweets()
    {
        $params = array(
            'userName' => 'RowlandBiznez',
            'consumerKey' => 'hgfhhgffhg',
            'consumerSecret' => 'hhffhfghfhf',
            'accessToken' => 'hfhhhfhhf',
            'accessTokenSecret' => 'hfhfhfhfhhfhfh',
            'tweetLimit' => 5 // the no of tweets to be displayed
        );
        $this->load->library('twitter', $params);
        $tweets = $this->twitter->getHomeTimeLine();
        $this->load->helper('tweet_helper');
        $mytweets = getTweetsHTML($tweets);

        return $mytweets;
    }
}

Then in each controller use that property when you load a view:

$this->load->view('path/to/view', array('tweets', $this->tweets));

Solution #2:

You could also load the tweets by sending a XHR request from the client to Controller/Method (after serving the page), then insert the response into the page by Javascript.

Here is a jQuery sample:

$.ajax({
    url      : <?php echo base_url('controller/method'); ?>,
    type     : 'GET',
    success  : function (result) {
        // Insert the result into a container
        $('#fresh-tweetfeed').append(result);
    }
});