`
天梯梦
  • 浏览: 13733433 次
  • 性别: Icon_minigender_2
  • 来自: 洛杉矶
社区版块
存档分类
最新评论

codeigniter + Ajax (亲测)

阅读更多

 

 

(E文,没时间翻译)

首先做一个Ajax的helper,下面是说明,很简单,粘贴复制就可以了。。。

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

function is_ajax()
{
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}

?> 
 

Copy the following code into a file. Save the file as ajax_helper.php and save in your application/helpers/ folder.

Load it if you need if by:

Normal loading

This is pretty much how we normally include helpers. This is the best approach unless you would use the ajax helper most of the time.

$this->load->helper('ajax');
 

Autoloading

Open your config.php file located at application/config/ . Look for this line.

 

$autoload['helper'] = array();
 

Add yours to the list

$autoload['helper'] = array('ajax');
 

You should not add _helper when adding it to the autoload['helper'] array.

 

下面是详细说明: 初中英语够你看懂以下内容了 (最后一行还有测试页面呢~~)

 

 

AJAX can be seen almost everywhere on the web. Yahoo uses it. Google uses it. My boss uses it. My grandmother uses it — well maybe not but that shouldn't stop you from using it.

Here's an awesome tutorial to use AJAX with CodeIgniter.

This tutorial assumes that you have a form set-up like so:

<?php echo form_open(current_url(), array('id' => 'registration_form'));?>
<label for="username">Username: </label>
<input type="text" class="span-2" value="" name="username" id="username" /><br />

<label for="first_name">First Name: </label>
<input type="text" value="" name="first_name" id="first_name" /><br />

<label for="last_name">Last Name: </label>
<input type="text" value="" name="last_name" id="last_name" /><br />

<label for="desc">Password: </label>
<input type="password" value="" name="password" id="password" /><br />

<label for="desc">Repeat Password: </label>
<input type="password" value="" name="passconf" id="passconf" /><br />

<label for="desc">Email: </label>
<input type="text" value="" name="email" id="email" /><br />

<label for="register"> </label>
<input type="submit" value="Register" name="register" id="register" class="update" />
</form>
 

The form starts with the usual form helper , form_open(). The rest is pretty much normal.

Now with the Javascript. In this tutorial, we will use jQuery

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
 

Now we do AJAX

Javascript

<script type="text/javascript">
$(document).ready(function() {
 $('#registration_form').submit(function(){
         $.post("<?php echo site_url(current_url());?>", {
             username: $('#username').val(), 
             first_name: $('#first_name').val(),
             last_name: $('#last_name').val(),
             password: $('#password').val(),
             passconf: $('#passconf').val(),
             email: $('#email').val(),
          },
          function(data){
                  alert(data);
          }
  );
  return false;
 });
});
</script>
 

Explanation

$.post("<?php echo site_url(current_url());?>", {
 

The fourth line of the previous code will request to the current url. This means that if you are on '/this/page/', it will request to '/this/page/'.

username: $('#username').val(), 
first_name: $('#first_name').val(),
last_name: $('#last_name').val(),
password: $('#password').val(),
passconf: $('#passconf').val(),
email: $('#email').val()

 

The above will be the information we will post. For example, username: $('#username').val() will pass the value of the element with the id, username. In our case, that would be one of the inputs.

function(data){
    alert(data);
}

 

The above is the callback. From here we accept the response from our request. In our case, we alert the response.

CodeIgniter

function ajax_with_codeigniter()
{
       $this->load->library('form_validation');
       $this->load->helper(array('ajax', 'form'));

       $this->form_validation->set_rules('username', 'Username', 'callback_username_check');
       $this->form_validation->set_rules('first_name', 'First Name', 'required');
       $this->form_validation->set_rules('last_name', 'Last Name', 'required');
       $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
       $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
       $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

       if ($_POST)
       {
                if (is_ajax() AND $this->form_validation->run() === TRUE)
                {
                    echo "Registration Successful";
                }
                else
                {
                    echo validation_errors(' ',' ');
                }
        }
        else
        {
         $this->load->view('code/ajax_with_codeigniter/ajax_with_codeigniter');
        }
}

 

Explanation

$this->load->library('form_validation');
$this->load->helper(array('ajax','form'));
 

The above code will load the library ajax helper, the form helper and the form validation library.

$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
 $this->form_validation->set_rules('first_name', 'First Name', 'required');
 $this->form_validation->set_rules('last_name', 'Last Name', 'required');
 $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
 $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
 $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

 

The above code is how we set rules. Pretty normal if you have used CodeIgniter in the past.

if ($_POST)
{
    if (is_ajax() AND $this->form_validation->run() === TRUE)
    {
        echo "Registration Successful";
    }
    else
    {
        echo validation_errors(' ', ' ');
    }
}
 else
{
    $this->load->view('code/ajax_with_codeigniter/ajax_with_codeigniter');
}

 

 

The last piece of code checks for anything POST ed. Remember that we are requesting to the same method so we should check for anything POST ed before we output anything. This conditional statement is only used because of the situation. You normally won't have this checkpoint.

There's something POST ed

When we know that there was something POST ed, we check if the request was done via the ajax_helper. This is just some check if we only want AJAX requests. The second part of the condition is if the data passed passes the validation rules we set up. If it checks out fine, we send our message, "Registration successful". If not, we send the errors.

Nothing was POST ed

When we know that nothing was POST ed, we load the view. This pretty much activates when we just loaded the page.

Demo

You can visit our AJAX with CodeIgniter demo .

分享到:
评论

相关推荐

    vue + vue-router +axios+ PHP + CodeIgniter + Mysql 项目管理系统.zip

    vue + vue-router +axios + element UI + PHP + CodeIgniter + Mysql 项目管理系统. 软件开发设计:应用软件开发、系统软件开发、移动应用开发、网站开发Node.js、C++、Java、python、web、C#等语言的项目开发与学习...

    php +CodeIgniter + jquery + 组件开发的二手车交易系统=&gt;毕设.zip

    jQuery是一个强大的JavaScript库,简化了HTML文档遍历、事件处理、动画制作和Ajax交互。在二手车交易系统中,jQuery用于优化前端用户体验,如:动态加载内容、表单验证、页面元素交互效果等,使用户操作更加流畅。 ...

    Laravel+Codeigniter+NodeJS+HTML 后台管理模板

    Codeigniter 入门项目 NodeJS 入门项目 令人惊叹的仪表板页面布局 使用 Bootstrap 4 构建 干净的代码 基于组件的结构 悬停效果 谷歌地图 易于定制 独特、干净和现代的设计 完全响应 跨浏览器优化 使用免费的 Google ...

    CodeIgniter+用户指南+v+2.1.0.zip

    CI是一套给 PHP 网站开发者使用的应用程序开发...它提供一套丰富的标准库以及简单的接口和逻辑结构,其目的是使开发人员更快速地进行项目开发。使用CI可以减少代码的编写量,并将你的精力投入到项目的创造性开发上。

    CodeIgniter资料+ci+jquery范例

    CodeIgniter+架构的说明教程.pdf CodeIgniter用户指南(版本1.7.2).chm CodeIgniter资料+ci+jquery范例.zip PHP 敏捷开发框架CodeIgniter.chm Wrox,.Professional.CodeIgniter.(2008).BBL.[0470282452].pdf

    CodeIgniter +Smarty集成

    在CodeIgniter中集成Smarty,主要是为了利用Smarty的模板系统,提供更好的视图层管理。Smarty允许你定义模板语言,将HTML与PHP代码分离,使界面设计更为直观,同时保持代码的清晰和可维护性。集成过程包括安装Smarty...

    Ajax-Codeigniter-3-Ajax-Form-Submission.zip

    Ajax-Codeigniter-3-Ajax-Form-Submission.zip,“codeigniter 3 ajax表单提交和验证教程”一集的源代码,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于创建...

    CodeIgniter and Ajax using jQuery.zip

    4. **Ajax与CodeIgniter的结合**:在CodeIgniter中,你可以创建一个专门处理Ajax请求的控制器方法,通过URL指定该方法。Ajax请求发送到这个URL,控制器处理请求后,可以通过JSON或XML格式返回数据,再由jQuery解析并...

    个人博客程序,基于CodeIgniter+Mysql.zip

    项目工程资源经过严格测试可直接运行成功且功能正常的情况才上传,可轻松copy复刻,拿到资料包后可轻松复现出一样的项目,本人系统开发经验充足(全栈开发),有任何使用问题欢迎随时与我联系,我会及时为您解惑,...

    Ajax-CodeIgniter-Ajax-Search.zip

    Ajax-CodeIgniter-Ajax-Search.zip,codeigniter ajax实时搜索,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于创建动态网页,其中网页的小部分在不重新加载网页...

    Ajax-codeigniter-ajax-crud.zip

    Ajax-codeigniter-ajax-crud.zip,使用codeigniter、jquery和ajax实现简单的crud,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于创建动态网页,其中网页的小...

    codeigniter-vue:CodeIgniter + VueJs-准备部署新项目

    在实际开发过程中,常见的做法是通过Ajax或Fetch API在客户端和服务器之间进行数据交换,实现前后端分离。 HTML(HyperText Markup Language)标签在“codeigniter-vue”项目中起着基础性的作用,它是网页内容的...

    基于PHP+MySQL+Ajax实现的在线二手书交易平台+源代码+详细文档

    在这个基于PHP+MySQL+Ajax实现的在线二手书交易平台项目中,涵盖了多项重要的IT技术与概念。首先,让我们深入了解这些核心组成部分: 1. **PHP**:PHP(Hypertext Preprocessor)是一种广泛使用的开源脚本语言,...

    CodeIgniter 3 + Vue.js 3 + Vite和受支持的热模块替换(HMR)-PHP开发

    只是一个基本示例,说明如何将CodeIgniter 3 + Vue.js 3 + Vite与支持的热模块替换(HMR)集成。 CodeIgniter 3 + Vue.js 3 + Vite这只是一个基本示例,说明如何将CodeIgniter 3 + Vue.js 3 + Vite与受支持的热模块...

    CodeIgniter-PHPStorm:Codeigniter 2.2.0 支持 PHPStorm

    CodeIgniter-PhpStorm CodeIgniter 2.2.1 支持 PhpStorm 8.0 如何 创建新项目时,克隆此存储库而不是 CodeIgniter 上的默认存储库。 使用 PhpStorm 打开文件夹。 仅将以下文件标记为纯文本: '系统/核心/...

    qms_entol_net:XCRUD + Codeigniter +管理引导

    XCRUD + Codeigniter +管理引导程序#引导程序#glyphicons #xcrud #codeigniter #trik #tips 管理员登录电子邮件: 密码:entol123 用户登录: 电子邮件: 密码:11111111 原始Google+发布 原始源代码:源代码: :

    基于 Codeigniter 3.0.6 + Smarty 3 + AdminLTE + RBAC 的后台管理系统.zip

    接下来,使用CodeIgniter的Model-View-Controller(MVC)架构设计模式,编写控制器来处理用户请求,模型来操作数据库,以及视图来展示数据。 Smarty 3 模板引擎则用于将HTML和PHP代码分离,开发者可以在Smarty模板...

Global site tag (gtag.js) - Google Analytics