Home > Backend Development > PHP Tutorial > PHP开发框架kohana中处理ajax请求的例子_PHP

PHP开发框架kohana中处理ajax请求的例子_PHP

WBOY
Release: 2016-06-01 11:51:57
Original
931 people have browsed it

Ajax

今天分享的是在kohana中处理页面的ajax请求.2步搞定.前提是你的kohana框架已经可以正确运行了,注意下.

1.页面发出请求.

现在主流的javascript框架非jQuery莫属.jQuery对ajax请求也作了封装,这里就以jQuery为例来写个.demo是获取后台json串,并且用each处理.代码大部分是从jqapi搞来的,准确也方便.

$.ajax({
 url: "/test/json",//test是控制器,json是action,带/是相对站点根目录的意思
 dataType:json,
// data: 这里的写法一般是拼字符串,'id=1&name=jack'这种.
 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');
 }
});
Copy after login

2.kohana中的处理,返回json串.上代码

public function action_json()
  {
    $this -> auto_render = FALSE;//不需要view
  
   if ($this -> request -> is_ajax()) //判断是否为ajax请求
   {
     //get $arr here.
    echo json_encode($arr);//建议这样写,避免0或其他情况.
    exit;
   
   }    
   // json 只支持 utf-8 编码,这点很重要,切记啊!!!    
}
Copy after login

ok,相信看完这2段代码,kohana中处理ajax请求,你肯定懂的.

PS:前台js必须是utf-8编码,要注意哦,亲.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template