简体   繁体   中英

Kohana/PHP/Ajax/ How to call controller and return HTML or a partial

Full disclosure, I haven't worked with Ajax before. I am starting to read up on guides but time constraints have me panicking and looking here for help.

Working with Kohana and am trying to figure out how to implement an infinite scroll. The application has existing pagination set up.

I've found that by doing this in my script:

$.post('mycontroller/infinite', {page:page}, function(data) {
    $('.mycontainer').append(data);
});

and setting up the action in my controller:

<?php
public function action_infinite(){
?><p>HELLO WORLD</p><?php
}
?>

The entire page is being appended to my div after the Hello World text. I set up an alert to see what was in data and it was literally the entire page of HTML starting with the p tag Hello World.

How do I go about returning a partial from my controller and not appending the entire page?

There are two ways to do infinite scrolling:

  1. Return HTML that you can paste directly into the page
  2. Return JSON data that you then use to generate and append HTML with Javascript

The first approach has the advantage that you don't need to rewrite your views twice. Assuming you're using plain old PHP templates, your code would go something like this:

Product page view:

<html>
<!-- blah blah blah -->
<div id="products">
<?php echo View::factory('products/page')->bind('page_num', $page)->bind('products', $products) ?>
</div>
<!-- blah blah -->

Page view

<?php foreach($products as $product): ?>
    <div class="product"><!-- blah blah --></div>
<?php endforeach ?>

Page fetch controller

public function action_page()
{
    $this->template->content = View::factory('products/page')->bind(...);
}

The main point is to separate the product page code from the actual code that renders the individual products. That way you can easily invoke only the product render code for things like infinite scrolling.

Note: I haven't used Kohana in years so could have made some minor mistakes.

OK so my main problem was that the entire page was in the response. I found out this was a Kohana thing. By placing this in my controller method:

$this->auto_render=false;

The response ceased to be bloated with HTML I didn't want.

Then I simply had to set my View::factory and echo it.

public function action_getjson()
{
    $this->response->headers('Content-Type', 'application/json; charset=utf-8');
    $this->auto_render = false;
    $this->response->body(json_encode(['var' => 'blabla'));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM