Javascript 使用$.parseJSON分析服务器响应失败
我有两个简单的函数:Javascript 使用$.parseJSON分析服务器响应失败,javascript,jquery,json,Javascript,Jquery,Json,我有两个简单的函数: function getBatchSliceInfo(batch_num){ //get the batch slice info for the batch_num alert('batch num is ' + batch_num); //returns the batch_num correctly $.getJSON("statistics_batchdb.jsp", {batch_number: batch_num, slice_stats
function getBatchSliceInfo(batch_num){
//get the batch slice info for the batch_num
alert('batch num is ' + batch_num); //returns the batch_num correctly
$.getJSON("statistics_batchdb.jsp", {batch_number: batch_num, slice_stats: 'true'}, showTable);
}
function showTable(data){
$("#table_slice_stats").hide();
if(data.error){
console.log("Something went wrong");
}
var jo = $.parseJSON(data);
alert('This JSON object has this many elements: ' + jo.length);
$.each(jo[0], function (i, val){
alert('This i value is' + i );
alert('This val value is' + val);
});
$("#table_slice_stats").show();
}
所以我点击一个按钮调用getBatchSliceInfo,得到JSON
响应似乎是正确的,所以服务器端我很好
但是,我没有将该响应正确地传递给showTable。“数据”似乎为空,因为在控制台中我得到错误:
Uncaught TypeError: Cannot read property 'length' of null batch_statistics_new.jsp:274
showTable batch_statistics_new.jsp:274
o jquery-1.7.2.min.js:2
p.fireWith jquery-1.7.2.min.js:2
w jquery-1.7.2.min.js:4
d jquery-1.7.2.min.js:4
我相信这是一个非常简单的语法问题,但我不知道发生了什么 检查您的
数据
var data= [{slice_name:Nutrion,iteration_zero:.....},{......},{......}]
转换为json格式后,您的数据如下所示
var data= {[{slice_name:Nutrion,iteration_zero:.....},{......},{......}]} //It not json format.
如果您尝试使用length属性,它会抛出异常。因此,在不解析为json的情况下也可以这样做。尝试不解析json,我猜它已经类似于yo=data,对于debuggin,请使用console.dir(data),您不会将json传递给
$.parseJSON
。您正在传递一个JavaScript对象,该对象是已解析JSON的结果。@johnSmith您和cookie monster完全正确。