所以,我开始使用Handlebars.js模板从Jquery GET请求中显示成功的html代码。然后我从我的Controller(从我的模型/数据库获取它)中获取一个数组。在Handlebars中,我必须使用Array名称来遍历它。我使用dataype JSON传递此数组,并在我的Controller中使用json_encoding($array}
。
问题是我的数组似乎没有得到数组名称,所以我没有要引用的数组名称。
模型中的代码:
public function getAllUserInfo() {
$this->selStmt->execute();
return $this->selStmt->fetchAll(PDO::FETCH_ASSOC);
}
控制器中的代码:
private function getUserInfo() {
$userInfo = $GLOBALS["userModel"];
$userModel = $userInfo->getSearchResult();
$data = json_encode($userModel);
echo $data;
}
View in View(Jquery):
$(function () {
$.ajax({
type: 'GET',
url: '?page=getUserInfo',
dataType: 'json',
success: function(data) {
createHTML(data);
$.each(data, function(i, item){
displayUsers(item);
});
}
});
});
displayUsers函数是把手功能。
我的问题是加载页面时我获取的数组如下所示:
[{"userID":"19","name":"Testbruker2","username":"Test2","password":"test123","userLevel":"user","image":"tafjord.jpg","lastLogin":null,"email":"test@test.no"},{"userID":"20","name":"Testbruker3","username":"Test3","password":"test123","userLevel":"user","image":"tafjord.jpg","lastLogin":null,"email":"test@test.no"}]
我想要这样的事情:
{
Pets: [
{
"name": "Meowsy",
"species" : "cat",
"foods": {
"likes": ["tuna", "catnip"],
"dislikes": ["ham", "zucchini"]
}
},
{
"name": "Barky",
"species" : "dog",
"foods": {
"likes": ["bones", "carrots"],
"dislikes": ["tuna"]
}
},
{
"name": "Purrpaws",
"species" : "cat",
"foods": {
"likes": ["mice"],
"dislikes": ["cookies"]
}
}
]
}
在我的车把容器中,我必须写:
{{#each ARRAYNAME}}
//code here
{{/each}}
但是我没有要引用的数组名称..
任何人都知道如何做到这一点?
谢谢。
答案 0 :(得分:2)
这将解决问题
$data = json_encode(array("DesiredArrayName" => $userModel));