发出访问json对象值的问题

我有一个问题console.logging从我的jquery ajax调用发送回脚本的json对象的值。

剧本:

for(i=0; i<IDs.length; i++) { var vendor = IDs[i]; $j.ajax({ type: "POST", url: "/ajax_calls/updatePrices.php", data: { 'vendorID': vendor, 'product_id': product_id} }).done(function(data) { console.log('The data is ' + data); var basePrice = simpleArray[vendor][colorSelected]; //if(data.tier2_range_start[i]) console.log('Range start is data.tier2_range_start: ' + data.tier2_range_start); if (qty  data.tier2_range_start){ simpleArray[vendor][colorSelected]= (basePrice * qty) * data.tier2_discount; } else if (qty > data.tier3_range_start){ simpleArray[vendor][colorSelected]= (basePrice * qty) * data.tier3_discount; } else if (qty > data.tier4_range_start){ simpleArray[vendor][colorSelected]= (basePrice * qty) * data.tier4_discount; } else if (qty > data.tier5_range_start){ simpleArray[vendor][colorSelected]= (basePrice * qty) * data.tier5_discount; } else{ console.log('Something went wrong'); } $j('.details'+vendor+ ' .priceBlock').empty(); $j('.details'+vendor+ ' .priceBlock').append(''+simpleArray[vendor][colorSelected]+''); }); }//end for 

脚本叫:

  query($sql) as $row) { $echoArray['vendor_id']= $row['vendor_id']; $echoArray['tier2_range_start']= $row['tier2_range_start']; $echoArray['tier2_range_stop']= $row['tier2_range_stop']; $echoArray['tier3_range_start']= $row['tier3_range_start']; $echoArray['tier3_range_stop']= $row['tier3_range_stop']; $echoArray['tier4_range_start']= $row['tier4_range_start']; $echoArray['tier4_range_stop']= $row['tier4_range_stop']; $echoArray['tier5_range_start']= $row['tier5_range_start']; $echoArray['tier2_discount']= $row['tier2_discount']; $echoArray['tier3_discount']= $row['tier3_discount']; $echoArray['tier4_discount']= $row['tier4_discount']; $echoArray['tier5_discount']= $row['tier5_discount']; } echo json_encode($echoArray); ?> 

数据记录为(例如,在没有空数据对象的循环上):

 [15:06:13.397] The data is {"vendor_id":"3","tier2_range_start":"5","tier2_range_stop":"20","tier3_range_start":"20","tier3_range_stop":"100","tier4_range_start":"100","tier4_range_stop":"500","tier5_range_start":"500","tier2_discount":"2","tier3_discount":"3.1","tier4_discount":"4.3","tier5_discount":"5"} 

为什么data.tier2_range_start未定义?

可能你的问题在于data[vendor].tier2_range_start

如果从服务器获得的所有响应都与示例相同( [Array, Array, Object] ),则只有vendor=2您的代码才会vendor=2 。 否则,您将尝试访问不存在的数组中的成员或访问不存在的元素。

因此,您可以检查是否使用IDs值作为索引实际上是您想要的。

我不得不把var data = JSON.parse(data); 在我的jquery。 谁知道为什么?

你需要告诉jQuery返回的数据是json,除非你在响应中放置一个合适的mime头,否则jQuery应该怎么知道?

在PHP开头的某个地方: header('Content-type: text/json');

在你的ajax:

 ... data: { 'vendorID': vendor, 'product_id': product_id}, dataType: "json", ... 

那么jQuery正在为你做这份工作。 你的踪迹应该是这样的

 [15:06:13.397] The data is Object object