【问题标题】:Display id using ajax to controller使用ajax向控制器显示id
【发布时间】:2017-06-21 10:23:25
【问题描述】:

您好,我是 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);

【问题讨论】:

  • 你的控制台有错误吗?
  • echo json_encode( array('id' =&gt; $category_id) );
  • 但是在ajax代码中我使用dataType:'json',成功函数不能报警
  • 因为您在 alert 之前重定向。看看我的回答@VidhiPatel

标签: php ajax codeigniter


【解决方案1】:

这里是新生需要在 CodeIgniter 中处理的所有信息 :)

首先通过.htaccess从CodeIgniter url中删除'index.php'。在 CodeIgniter 'index.php' 所在的位置创建 .htaccess 文件。

.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

如何在 WAMP 中手动启用 mode_rewrite

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

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

3 - 如果您使用的是 XAMPP 或 WAMP 包,那么您将找到该文件 在:{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 None 并将其替换为 AllowOverride All

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

自动设置“base_url”

/*
|--------------------------------------------------------------------------
| 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 Form Helper。否则你将无法通过 ajax 或 Form POST POST 参数或调用控制器方法)

$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!! ....

【讨论】:

  • 创建这个文件 .htaccess 需要哪个位置
  • 你可以在你的项目根目录下创建 Codeigniter index.php 文件
  • 在没有 index.php 页面的 url 中出现错误是找不到页面所以我需要使用 index.php
  • 当我 dataType:'json' 时,你好 Neeraj Singh,总是我的 javascript 警报错误并且没有 json 我无法将我的数据接收到控制器
  • @VidhiPatel,请分享您的表单操作 url.. 确保是否可以通过 url 访问.. 检查浏览器控制台所获得的 ajax 响应..
【解决方案2】:

很简单,在你的 Controller 函数 add_to_cart 中这样做:

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

只是不要添加它的 json_encode() 。 然后,如果您想返回您的 ajax 请求,只需这样做

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

应该可以的。

如果不行就评论。

谢谢,

【讨论】:

  • 是你的url:&lt;?php echo site_url(); ?&gt;/Home/add_to_cart 去正确的控制器吗?并删除您的window.location.href = '&lt;?php echo base_url(); ?&gt;index.php/Home/add_to_cart';,使其不会重新加载。
  • 我认为您必须像这样更改您的 ajax url。 url: '&lt;?php echo base_url(); ?&gt;index.php/home/add_to_cart', 如果有 index.php 但如果你没有使用 ` url: 'home/add_to_cart',`
【解决方案3】:

在控制器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';

            },

【讨论】:

  • 成功函数不能报警
【解决方案4】:

试试这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2017-03-11
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多