作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我应该如何转换我的 JSON 输出。这样就可以使用 J Query 轻松地对其进行迭代。
我正在使用 CakePHP Controller 在 MySql 查询后生成 JSON。
没有 Trick 的 CakePHP 有帮助吗?
我得到输出为
在 View 中输出
[{"8":"Young"},{"9":"Child"},{"10":"Old"},{"11":"Large"}]
我需要输出为
[{ "id":"8", "name": "Young" }, { "id": "9", "name": "Child" }, { "id": "10", "name": "Old" },{ "id":"11", "name": "Large" }]
Controller -> gettype 方法
if ($this->RequestHandler->isAjax()) {
if(isset($this->request->data['typeid'])){
$listType= array();
$arrayOfIds = explode(',',$this->request->data['TypeIds']);
foreach($arrayOfIds as $TypeId) {
$listType[] = $this->Type->find('list', array(
'conditions' => array(
'Type.id' => $TypeId
),
'fields' => array('Type.name')
));
}
echo json_encode($listType);
}
}
View 中的 AJAX
var dataType = 'typeid='+ typeid+'&TypeIds='+ TypeIds;
var urlToGetType = absUrl+"gettype/";
$.ajax({
type: "post",
dataType: "json",
url: urlToGetType,
data: dataType,
success: function (resTypeData, status) {
console.log(resTypeData);
},
error: function (xhr, desc, err) {
}
});
最佳答案
好吧,我明白了为什么我的原始解决方案不起作用:您在 find() 上调用“列表”方法,它生成的输出为:
Array
(
[id] => 'displayValue',
[1] => 'displayValue1',
[2] => 'displayValue2',
)
改用 find('all') :
[ModelName] => Array
(
[id] => 83
[field1] => value1
[field2] => value2
[field3] => value3
)
然后再次设置以下内容:
'fields' => array('Type.id', 'Type.name')
这是 CakePHP Retrieving Your Data Documentation .
关于php - 如何在 CakePHP Controller 中获取格式化的 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24920282/
我是一名优秀的程序员,十分优秀!