tho*_*uts 6 mysql ajax symfony doctrine-orm
我正试图获得一个AJAX响应,所以我可以摆弄它,使我的表单更容易使用.当我使控制器(下面的代码)返回正常响应时var_dump(),我得到对象的输出,所以我知道查询没有错(我使用ID 1来查询调试).但是,当我返回输出时json_encode(),我只得到一个空的JSON文件.
<div id="content">
<form id="myForm" action="{{path('snow_ajax')}}" method="POST" >
Write your name here:
<input type="text" name="name" id="name_id" value="" /><br />
<input type="submit" value="Send" />
</form>
</div>
Run Code Online (Sandbox Code Playgroud)
<script type="text/javascript">
$(document).ready(function() {
$("#myForm").submit(function(){
var url=$("#myForm").attr("action");
$.post(url,{
formName:"ajaxtest",
other:"attributes"
},function(data){
if(data.responseCode==200 ){
alert("Got your json!");
}
else{
alert("something went wrong :(");
}
});
return false;
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
public function ajaxAction()
{
$location = $this->getDoctrine()->getRepository('SnowFrontBundle:Location')
->find(1);
$output = var_dump($location);
return $output;
}
Run Code Online (Sandbox Code Playgroud)
public function ajaxAction()
{
$location = $this->getDoctrine()->getRepository('SnowFrontBundle:Location')
->find(1);
return new Response(json_encode($location), 200);
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮帮我吗?这让我疯了!
我设法通过使用Doctrine2的实体管理器来修复它,以便在数组中获得结果,之后我继续将其编码为JSON.我不确定这是否是最干净的方法(根据我的IDE,getEntityManager()似乎已被弃用)但它现在工作正常.
public function ajaxAction()
{
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery('SELECT l FROM Snow\FrontBundle\Entity\Location l WHERE l.id=:id');
$query->setParameter('id', 1);
$result = $query->getArrayResult();
return new Response(json_encode($result), 200);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5349 次 |
| 最近记录: |