用户
 找回密码
 入住 CI 中国社区
搜索
查看: 4903|回复: 3
收起左侧

详细讲述一个简单的Ajax请求(绝对原创)

[复制链接]
发表于 2012-2-23 14:38:11 | 显示全部楼层 |阅读模式
     一:  在论坛里看到许多初学者对在CI中怎样使用ajax比较迷茫,我个人的观点是尽量不要使用CI里封装好的,因为使用CI封装好的,你还得遵循它要求的格式去写,这样更容易让初学者糊涂。
     二:我的目录结构如下:
           1:http://localhost/testjquery/为我的根目录
           2:根目录下有assets文件夹和system文件夹和index.php。其中assets文件夹里放置我的公共项。比如说CSS和JS
           3:http://localhost/testjquery/assets/js/下放置JS库。
           4:控制器下有ajax.php    路径:E:\WEB\testjquery\system\application\controllers
           5:视图有template.php   路径:E:\WEB\testjquery\system\application\views
           6:js有jquery-1.7.js和global.js,路径:E:\WEB\testjquery\assets\js
     三:详细的代码如下:
          1:ajax.php:
<?php
/*
* 控制器
*/
  class Ajax extends Controller{
      function __construct(){
          parent::__construct();
      }
      function index(){
          $data['title']="CI的Jquery";
          $this->load->view('template',$data);
      }
      function username(){
          $user=trim($_POST['user']);
          echo $user;
      }
  }
?>
2:视图template.php   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--  the following two lines load the JQuery library and JavaScript files -->
<script src="./assets/js/jquery-1.7.js" type="text/javascript" ></script>
<script src="./assets/js/global.js" type="text/javascript" ></script>
<title><?php echo $title;?></title>
</head>
    <body>
     这是模板页
     <input type="submit" value="点击" id="dian" name="dian"/>
    </body>
</html>
3:global.js
jQuery(function($){
   $("#dian").click(function(){
    $.post('./index.php/ajax/username',{'user':'关羽和张飞'}, function(r){
         alert(r);
       })
     }
    )
  }
)
代码非常简单,初学者可以照着步骤进行测试。
注意里面有的URL路径要带上".",否则会被解析成错误的URL,以至于取不到结果。{:soso_e100:}


发表于 2012-5-20 21:15:44 | 显示全部楼层
这么好的文章怎么没人顶,很适合小白新手
发表于 2013-3-27 20:11:15 | 显示全部楼层
学习来了
发表于 2013-5-3 17:51:33 | 显示全部楼层
新手寶物!! 謝謝!!

本版积分规则