An example of processing ajax requests in PHP development framework kohana

  • 2021-07-09 07:29:34
  • OfStack

Today we share ajax requests for processing pages in kohana. Step 2 is done. If your kohana framework is working properly, please note.

1. The page makes a request.

Now the mainstream javascript framework is not jQuery. jQuery ajax request is also encapsulated, here to jQuery as an example to write a. demo is to obtain the background json string, and with each processing. Most of the code is from jqapi, accurate and convenient.


$.ajax({
 url: "/test/json",//test Is the controller ,json Yes action, Belt / It means relative to the root directory of the site 
 dataType:json,
// data:  The way it is written here 1 It is like spelling a string ,'id=1&name=jack' This .
 success: function(data){
  var items = [];
  
 $.each(data, function(key, val) {
  items.push('<li id="' + key + '">' + val + '</li>');
 });
  
 $('<ul/>', {
  'class': 'my-new-list',
  html: items.join('')
 }).appendTo('body');
 }
});

2. Processing in kohana, returning an json string. Code on


public function action_json()
  {
    $this -> auto_render = FALSE;// No need view
  
   if ($this -> request -> is_ajax()) // Determine whether it is ajax Request 
   {
     //get $arr here.
    echo json_encode($arr);// It is suggested to write like this , Avoid 0 Or other circumstances .
    exit;
   
   }    
   // json  Support only  utf-8  Code , This is very important , Remember that !!!    
}

ok, I believe that after reading these two pieces of code, kohana processing ajax request, you must understand.

PS: The foreground js must be utf-8 encoded. Be careful oh, dear.


Related articles: