我的PHP是:
if(!empty($_POST)&&($_POST['action']=='edit'))
{
foreach ($_POST['selected'] as $edit_id)
{
$query = "SELECT * FROM grocery WHERE id = $edit_id";
$result = dbQuery($query);
break;
}
$rowArr=array();
$inRow = mysqli_fetch_array($result);
$id = $inRow['id'];
$shop = $inRow['shop'];
$category = $inRow['category'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
array_push($rowArr, array('id' => $id, 'shop' => $shop, 'category' =>$category, 'item' => $item, 'qnty' => $qnty, 'unit' => $unit, 'price_based_on' => $price_based_on, 'mrp' => $mrp, 'sellers_price' => $sellers_price, 'last_updated_on' => $last_updated_on));
echo json_encode(array('rowArr' => $rowArr));
}
上述脚本生成的输出(JSON)是:(我确保这是在Chrome控制台中生成的)
{
"rowArr": [
{
"id": "30",
"shop": "Subhash",
"category": "Spices",
"item": "Duta Corriander Powder",
"qnty": "50",
"unit": "gm",
"price_based_on": "Packet",
"mrp": "15.00",
"sellers_price": "12.00",
"last_updated_on": "2016-12-03"
}
]
}
我的jQuery是:
$('#edit').click(function(){
var data = $("#list :input").serialize();
$.post($("#list").attr('action'), data, function(json)
{
if(json.rowArr.length>0)
console.log("Data Exists");
else
console.log("Empty");
currentRow = json.rowArr[0];
console.log(json.rowArr[0].id);
$("#id").val(currentRow.id);
$("#id_disp").val(currentRow.id);
});
});
奇怪的是,Data Exists
或Empty
都不是由上述循环产生的。当我尝试访问JSON数据时,json.rowArr[0].id
我收到以下错误:
未捕获的TypeError:无法读取属性'长度'未定义的
为什么会这样?我该如何解决?
答案 0 :(得分:1)
您应该明确告诉jQuery您的响应具有JSON格式。根据{{3}},您应该将'json'
作为$.post
的第四个参数传递。
$('#edit').click(function(){
var data = $("#list :input").serialize();
$.post($("#list").attr('action'), data, function(json) {
if(json.rowArr.length>0)
console.log("Data Exists");
else
console.log("Empty");
currentRow = json.rowArr[0];
console.log(json.rowArr[0].id);
$("#id").val(currentRow.id);
$("#id_disp").val(currentRow.id);
}, 'json');
});