我一直在研究这段代码已有一段时间了,并研究过如何解决它的各种解决方案,但我没有找到。
我收到以下json数据:
{"id":"4","name":"bugatti","details":"the bugatti v8 simplly the best","seats":"2","status":"0","image"
:"","category":"sedean"}{"id":"5","name":"bently","details":"the bently the best of the best","seats"
:"5","status":"0","image":"","category":"SUV"}
我无法解析我从jquery ajax $ .post请求获得的json数据,如下所示:
$.post('response.php',
{
task : 'fleet'
},
function(data)
{
data = $.parseJSON(data);
$.each(data , function (key,value)
{
console.log(value);
});
console.log(data.id);
}
).error(
function()
{
}
).success(
);
这是response.php数据:
if(isset($_POST['task']) && $_POST['task'] == 'fleet')
{
$car = new Cars();
$fleet = $car->getAll();
foreach( $car->data() as $cars )
{
echo json_encode($cars);
}
}
可能是什么问题?
答案 0 :(得分:0)
我会做这样的事情
您还可以将dataType: 'json'
添加到$ .post函数中。
// making sure we pass the header for the json output
header('Content-Type: application/json');
// if $car->data() (is the array, just encode it to json)
echo json_encode($car->data());
我用你的代码运行了一些例子(没有ajax)
var data = '{"id":"4","name":"bugatti","details":"the bugatti v8 simplly the best"}';
data = $.parseJSON(data);
$.each(data , function (key,value)
{
console.log(value);
});
// key will output id, name, details..
// value will output (what is below)
输出:
4
bugatti
the bugatti v8 simplly the best
(删除value.id
,然后说value
)
如果你想确认参数,你可以轻松做到
if (key == 'id')