[英]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没有这些参数,您应该在ajax调用中传递这些ID,以便获得
$.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脚本中将值js传递给globe 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);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.