Ami*_*lhi 3 php ajax model-view-controller symfony
我是 Symfony 的新手,我想做一些操作,这样我可以通过 Ajax 获取实体主题中所有元素的列表,但答案仍然是“未定义”这里的代码文本很强
\n\n视图
\n\n $(document).ready(function () {\n var $theme = $(\'#theme\');\n $theme.append(\'<option value="">Choisir un th\xc3\xa8me</option>\');\n $.ajax({\n type: \'post\',\n url: \'{{ path(\'web_site_liste_theme_cmb\') }}\',\n dataType: \'json\',\n beforeSend: function () {\n $(\'#themediv\').append(\'<div id="loading" style=" float: left; display: block;"><img src="{{ asset(\'bundles/BackBundle/img/loadingicon.gif\') }}"/></div>\');\n },\n success: function (json) {\n {#$(\'#theme\').append({{ dump(json)}});#}\n console.log(json.value);\n $.each(json, function (index, value) {\n\n //console.log(value);\n $(\'#theme\').append(\'<option value="\' + value.id + \'">\' + value.name + \'</option>\');\n $(\'#loading\').remove();\n });\n }\n });\n });\nRun Code Online (Sandbox Code Playgroud)\n\n控制器
\n\n public function ListeThemeAction(Request $request)\n{\n\n $em = $this->getDoctrine()->getEntityManager();\n if ($request->isXmlHttpRequest()) {\n $themes = $em->getRepository(\'WebSiteBackBundle:theme\');\n $themes = $themes->findAll();\n //var_dump($themes);\n\n return new JsonResponse($json);\n }\n return new JsonResponse(\'no results found\', Response::HTTP_NOT_FOUND); // constant for 404\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n服务器响应是 200 OK,一切似乎都正常,我在数据库中有相同数量的数据,但我无法读取对象值
\n\n这是:\n console.log(json)
\n有很多方法可以做到这一点;我将向您展示其中之一。
首先,准备数据以从控制器发送数据并返回一个JsonResponse实例:
public function fooAction()
{
$data = ['foo1' => 'bar1', 'foo2' => 'bar2'];
return new JsonResponse($data); // or $this->json($data) since Symfony 3.1
}
Run Code Online (Sandbox Code Playgroud)
告诉
JsonResponse浏览器发送的数据必须解释为 JSON;否则,这些数据默认被解释为纯文本。
其次,使用相同的数据结构通过 JavaScript 回调函数访问它:
$.post('{{ path('web_site_liste_theme_cmb') }}', function (data) {
console.log(data['foo1']); // output: bar1
console.log(data.foo2); // output: bar2
});
Run Code Online (Sandbox Code Playgroud)
在您的问题中,发送的数据是一个对象数组,因此您需要查看此变量“json”(数组)并访问该对象的每个属性。