Codeigniter: Ajax请求,控制器中的全局变量


Codeigniter: Ajax Request, global variable in controller

在__construct()中设置全局变量;

function __construct()
{
        parent::__construct();
        //variables
        $this->galleryID = $this->uri->segment(3);
        $this->productID = $this->uri->segment(4);
}

从下拉菜单中做出选择后,我做了一个ajax请求。

$.ajax(
    {
        type: 'POST',
        url: '/beta/checkout/getCoverSizes',
        data: {
            column: size
        },
        dataType: 'json',
        success: function (json)
        {
            console.log(json);
        }
    });

此时,只需输出全局变量

public function getCoverSizes()
    {
        print_r($this->productID);
}

目前$this->productID返回0,我确信它是正确的,因为函数index()依赖于这个变量,并且正确地呈现数据。ajax请求似乎没有访问全局变量$this->productID.

$.ajax(
    {
        type: 'GET',  // use GET here
        url: '/beta/checkout/getCoverSizes',
        data: {
            column: size
        },
        dataType: 'json',
        success: function (json)
        {
            console.log(json);
        }
    });

您使用$this->uri->segment(3);galleryID$this->uri->segment(4);productID,但在ajax调用的url没有这些参数,您应该通过这些id在ajax调用,以获得像

$.ajax(
{
    type: 'POST',
    url: '/beta/checkout/getCoverSizes/1/2',
    //url: '/beta/checkout/getCoverSizes/galleryID/productID',
    data: {
        column: size
    },
    dataType: 'json',
    success: function (json)
    {
        console.log(json);
    }
});

在你们的课程中我假设你们已经定义了全局变量,比如

class checkout extends CI_Controller {
public $galleryID;
public $productID;
// your other code
}

在java-script中将值js传递给全局ajax

$("#abc").on("change",function(){
var post_data = new FormData();
ajax_request("dashboard/ajax",post_data, response,null);
});

然后在JS中

function ajax_request(URL, request_data, response_function, element){
    $.ajax({
        type: "POST",
        datatype:"json",
        url: BASE_URL+URL,
        data: request_data,
        mimeType: "multipart/form-data",
        contentType: false,
        cache: false,
        processData: false,
        success: function(result){
            response_function(JSON.parse(result), element);
        },
        error: function() {
            response_function(undefined, element);
        }
    });
}