我正在使用opencart。这里我从控制器获取数据,需要在前端显示。所以我写的代码如下:
这是控制器代码:
public function filter($setting) {
$this->load->language('module/color_filter');
$json = array();
if ($this->request->server['REQUEST_METHOD'] == 'POST' && isset($this->request->post['color'])) {
$colors = explode(',',$this->request->post['color']);
$products_arr = array();
foreach ($setting['color'] as $setting_col) {
foreach ($colors as $color) {
if ($setting_col['color_name'] === $color) {
$products_arr = array_merge($products_arr,array_values($setting_col['products']));
}
}
}
$this->load->model('catalog/product');
$products =array();
foreach ($products_arr as $product) {
if (!in_array($product,$products)) {
$products[] = $product;
}
}
$json['success'] = $products;
} else {
//$json['error'] = $this->language->get('error_color');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
从上面的代码我通过ajax得到$ json ['成功']数据如下:
Html代码:
<div class="panel panel-default">
<div class="panel-heading"><?php echo $heading_title; ?></div>
<div class="list-group filter-group">
<div class=" list-group-item color-swatches">
<?php foreach ($colors as $color) { ?>
<div class="checkbox">
<input type="checkbox" name="color-filter[]" data-toggle="tooltip" data-original-title="<?php echo $color['color_name']; ?>" value="<?php echo $color['color_name']; ?>" style="background:<?php echo $color['color_code']; ?>; " />
</div>
<?php } ?>
<?php foreach ($setting as $set) { ?>
<div><?php print_r($set); ?></div>
<?php } ?>
</div>
</div>
</div>
JS代码:
(function($) {
$(function() {
$('.color-swatches input[type=\'checkbox\'').on('click',function() {
var color = [];
$('input[name^=\'color-filter\']:checked').each(function(element) {
color.push(this.value);
alert("color names:"+color);
});
$.ajax({
url: 'index.php?route=module/color_filter',
type: 'post',
data: 'color=' + color,
dataType: 'json',
beforeSend: function() {
$('.category-products+.clearfix').remove();
},
complete: function() {
},
success: function(json) {
$('.category-products').each(function() {
var el = $(this);
console.log("$this value:"+$(this));
var re = /\('(\d+)'/;
var sr = el.find('button').attr('onClick').match(re)[1];
alert("json:"+json['success']);
if (json['success'].indexOf(sr) !== -1) {
el.fadeIn('slow');
} else {
el.fadeOut('slow');
}
});
}
});
});
});
})(window.jQuery);
我收到以下错误: 未捕获的TypeError:无法读取属性&#39;匹配&#39;未定义的
任何人都可以帮助解决问题。