通过ajax或者axios获取后端text形式json数据时,在使用前,需要转换成js的对象,有2种方法:
一、使用JSON.parse来回转换,会经常报错,不推荐。
二、使用eval强制转换。会偶尔报错。
1、当数据是{}形式,可能就报错了,解决办法是,在字符外包裹()小括号来解决;
2、当数据里面有换行符时,上面加小括号的方法也不适用,就需要对字符串进行处理,如下:
eval("(" + res.data.replace(/\n/g,'') + ")");
至此,问题完美解决!
补充,再次出现报错:.replace is not a function at ,应该市data此时又是对象了
3、此时在对data做toString处理。
当能正常解析的时候,用上述方法也报错,需要对返回的结果做是否对象的判断,然后在做字符处理,最终的处理逻辑如下:
this.$http.get(url,{params:{page:this.page,limit:10}}).then(function(res){
console.log(res.data);
if((res.data instanceof Object) && (res.data.code==0)){
this.tableData=res.data.data;
this.count=res.data.count;
}else{
console.log('出现异常');
let list = eval("(" + res.data.replace(/\r\n/g,'').replace(/\n/g,'') + ")");
this.tableData = list.data;
this.count = list.count;
}
console.log("success")
}.bind(this)).catch(function(e){
console.log(e)
})