出现这个问题的原因是因为后台传给前台的数据出现了问题,ajax对于json的格式特别的严格
下面是会出现这个问题的ajax请求
$.ajax({
type: "GET",
url: '{{url('/service/category')}}'+'/parent_id/' + parent_id,
dataType: 'json',
cache: false,
success: function(data) {
console.log("获取类别数据:");
console.log(data);
if(data == null) {
$('.bk_toptips').show();
$('.bk_toptips span').html('服务端错误');
setTimeout(function() {$('.bk_toptips').hide();}, 2000);
return;
}
if(data.status != 0) {
$('.bk_toptips').show();
$('.bk_toptips span').html(data.message);
setTimeout(function() {$('.bk_toptips').hide();}, 2000);
return;
}
$('.weui_cells_access').html('');
for(var i=0; i<data.categorys.length; i++) {
var next = '{{url('/product')}}'+'/category_id/' + data.categorys[i].id;
var node = '<a class="weui_cell" href="' + next + '">' +
'<div class="weui_cell_bd weui_cell_primary">' +
'<p>'+ data.categorys[i].name +'</p>' +
'</div>' +
'<div class="weui_cell_ft"></div>' +
'</a>';
$('.weui_cells_access').append(node);
}
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
问题主要是出在了dataType:'json',这行代码,这行代码的意思就是接收回传的数据为json格式。这个时候,我们只需要删除这段代码,就会接收到字符串格式的数据,然后再进行转换成json格式,下面是代码
$.ajax({
type: "GET",
url: '{{url('/service/category')}}'+'/parent_id/' + parent_id,
cache: false,
success: function(data) {
data=eval('('+data+')');
console.log("获取类别数据:");
console.log(data);
if(data == null) {
$('.bk_toptips').show();
$('.bk_toptips span').html('服务端错误');
setTimeout(function() {$('.bk_toptips').hide();}, 2000);
return;
}
if(data.status != 0) {
$('.bk_toptips').show();
$('.bk_toptips span').html(data.message);
setTimeout(function() {$('.bk_toptips').hide();}, 2000);
return;
}
$('.weui_cells_access').html('');
for(var i=0; i<data.categorys.length; i++) {
var next = '{{url('/product')}}'+'/category_id/' + data.categorys[i].id;
var node = '<a class="weui_cell" href="' + next + '">' +
'<div class="weui_cell_bd weui_cell_primary">' +
'<p>'+ data.categorys[i].name +'</p>' +
'</div>' +
'<div class="weui_cell_ft"></div>' +
'</a>';
$('.weui_cells_access').append(node);
}
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
data=eval('('+data+')');//这段代码就是将字符串转换成json格式