使用ajax到控制器显示id

时间:2017-06-21 10:23:25

标签: php ajax codeigniter

你好我是ci的新手,我想使用ajax从codeigniter传递到视图到控制器。如果我添加dataType:' json',那么我的ajax无法工作,我想从控制器回显数据

<script type="text/javascript">
$(document).ready(function() {
        $(".cart").click(function(){
         var subid=$(this).attr('data-index');
         alert(subid);
         $.ajax({
            url: '<?php echo site_url(); ?>/Home/add_to_cart',
            type: "POST",
            data: {
                subid: subid
            },
            dataType:'json',
            success: function(data) {
                window.location.href = '<?php echo base_url(); ?>index.php/Home/add_to_cart';
                 alert(data);
            },
            error: function(xhr, status, error) {
                 var error=xhr.responseText;
        //       alert(error);
              }

        });
    });
}); 
 </script> 

控制器       我想在ajax发送请求时回显类别ID

$category_id = $this->input->post('subid');
echo json_encode($category_id);

4 个答案:

答案 0 :(得分:0)

在控制器echo中,标题如下

php

header("Content-Type: application/json", true);
echo json_encode(array('id'=>$category_id));

Ajax :更改您的成功功能代码顺序

success: function(data) {
               console.log(data);
               temp = JSON.parse(data);
               alert(temp.id);
               //window.location.href = '<?php echo base_url(); ?>index.php/Home/add_to_cart';

            },

答案 1 :(得分:0)

这很简单,在你的Controller功能中,add_to_cart就是这样做的:

$category_id = $this->input->post('subid');
echo $category_id;

不要添加它的json_encode()。 然后,如果你想返回你的ajax请求就像这样做

success: function(data) {
          alert(data);
},

那应该是有效的。

只是评论它是否无效。

谢谢,

答案 2 :(得分:0)

试试这个

$.ajax({
            type:'POST',
            url:'<?php echo base_url();?>.'/Home/add_to_cart',
            data:{'subid':subid},
            success:function(data){
                //location.reload();
            }
        });

答案 3 :(得分:0)

以下是有关Freshers在CodeIgniter中需要处理的所有信息:)

  

首先删除&#39; index.php&#39;来自CodeIgniter网址的.htaccess。创建.htaccess文件,其中CodeIgniter&#39; index.php&#39;存在。

.htaccess 使用Windows,只需将任何空白文本文件重命名为 .htaccess。 创建一个.htaccess文件,这么简单......

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule .* index.php/$0 [PT,L] 
</IfModule>

如何在WAMP中启用mode_rewrite enter image description here

如何在WAMP中手动启用mode_rewrite

1 - 使用您喜欢的文本编辑器打开apache的配置文件。

2 - 配置文件通常位于: {apache_dir} /conf/httpd.conf

3 - 如果您使用的是XAMPP或WAMP包,那么您将找到该文件 at: {xampp_dir} /bin/apache/apache-xxx/conf/httpd.conf {wamp_dir} /bin/apache/apache-xxx/conf/httpd.conf

4 - 搜索以下字符串: #LoadModule rewrite_module modules / mod_rewrite.so 并取消注释(删除“#”符号)。

5 - 现在搜索另一个字符串 AllowOverride 无,并将其替换为 AllowOverride All

6 - 最后保存更改,关闭文本编辑器并重新启动Apache服务器

设置&#39; base_url&#39;自动

/*
|--------------------------------------------------------------------------
| Dynamic Base Url
|--------------------------------------------------------------------------
| Put below code in 'index.php' on top
|
*/
    define('APP_URL', ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . "://{$_SERVER['SERVER_NAME']}".str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME'])); 

配置设置

/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
|   http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = APP_URL;

/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';

配置CSRF设置 如果您没有在表单中传递CSRF令牌,或者没有使用CodeIgniter表单助手。否则您将无法POST参数或通过ajax或表单POST调用Controller方法

$config['csrf_protection'] = FALSE;
  

现在,问题答案:(

<强> 的JavaScript

<script type="text/javascript">
        $(document).ready(function() {
            // define base url
            var _CI_BASE_URL_ = "<?php echo site_url(); ?>";
            /**
             * ---------------------------
             * Example -1 with Url Params
             * ---------------------------
             */
            // on click cart button call ajax
            $(".cart").click(function(e){
                // stop default button behaviour
                e.preventDefault();
                // get subid from button attr
                var subid = $(this).data('index');
                // ajax function
                $.ajax(
                {
                    // *Notice: just send 'subid' with ajax url and CodeIgniter will take it from url
                    url: _CI_BASE_URL_ + 'home/add_to_cart/' + subid, 
                    // method
                    type: "POST",
                    // data type
                    dataType:'json',
                    // success callback
                    success: function(data) {
                        // why server response, we already have subid in JavaScript vars
                        // we can user that same to redirect in url
                        window.location.href = _CI_BASE_URL_ + 'home/add_to_cart/' + subid;
                    },
                    // ohh! we got error
                    error: function(xhr, status, error) {
                        // get ajax error
                        var error = xhr.responseText;
                        alert('Request made some error: ' + error);
                    }
                });
            });
            /**
             * ---------------------------
             * Example -2 with POST Params
             * ---------------------------
             */
            // on click cart button call ajax
            $(".cart").click(function(e){
                // stop default button behaviour
                e.preventDefault();
                // get subid from button attr
                var subid = $(this).data('index');
                // ajax function
                $.ajax(
                {
                    // just send subid with url and CodeIgniter will take from url
                    url: _CI_BASE_URL_ + 'home/add_to_cart_another', 
                    // method
                    type: "POST",
                    // POST params
                    data: {subid: subid},
                    // data type
                    dataType:'json',
                    // success callback
                    success: function(data) {
                        // if got the JSON with key cat_id
                        if(data.cat_id){
                            // if you want to alert, first alert then redirect
                            alert('CodeIginter retuned Cat ID: ' + data.cat_id);
                            // redirect user now..
                            window.location.href = _CI_BASE_URL_ + 'home/add_to_cart_another/' + data.cat_id;
                        }else{
                            alert('Category ID not return or null...');
                        }
                    },
                    // ohh! we got error
                    error: function(xhr, status, error) {
                        // get ajax error
                        var error = xhr.responseText;
                        alert('Request made some error: ' + error);
                    }
                });
            });
        }); 
    </script> 
  

现在CodeIgniter控制器:( :(

<?php
// Security First Matters...
(defined('BASEPATH') or exit('No direct script access allowed'));

/**
 * Class Home CI Controller
 */
class Home extends CI_Controller
{
    /**
     * Default run method
     * @return [type] [description]
     */
    public function index()
    {
        $this->load->view('home');
    }

    /**
     * [add_to_cart description]
     * @param [type] $cat_id [description]
     */
    public function add_to_cart($cat_id)
    {
        /**
         * Codeigniter is enough smart to take parameters if passed in url
         * if url is 'http://localhost/CodeIgniter/home/add_to_cart/100'
         * '100' will be assign to $cat_id by CodeIgniter
         *
         * intval to make sure only integer
         */
        // echo response for ajax call as JSON
        echo json_encode(array('cat_id' => intval($cat_id)));
    }

    /**
     * [add_to_cart description]
     * @param [type] $cat_id [description]
     */
    public function add_to_cart_another()
    {
        /**
         * get cat id from post and sanitize by passing 2nd param as true for XSS Clean,
         * Security always matters...
         *
         * intval to make sure only integer
         */
        $cat_id = $this->input->post('subid', true);
        // echo response for ajax call as JSON
        echo json_encode(array('cat_id' => intval($cat_id)));
    }
}
/* End of file home.php */
/* Location: ./application/controllers/home.php */

现在,我要睡觉了......:D Tada !! ....