0

这是我第一次在 Symfony 环境中涉足 Ajax,我可能对代码的组织方式有些困惑。

假设我的 ajax 调用如下所示:

$.getJSON('module/getMeSomeJSONThroughAjax', function(data) {console.log(data); } )

在我的模块/操作文件夹中,actions.class.php 文件有一个方法:

public function getMeSomeJSONThroughAjax()
{
   // do something
   return $jsonEncodedString;
}

请记住,我是not creating a template for the above method,因此我没有大多数其他操作那样的执行前缀。只是因为我不认为创建模板对于仅获取 AJAX HTTP 请求的 JSON 数据是一种过度杀伤的情况。

但是,当我的浏览器中发生触发 Ajax 调用的事件时,我的控制台会记录以下内容:

> Failed to load resource: the server responded with a status of 404
> (Not Found)
> http://localhost:8080/customerview_dev.php/flashcard/getMeSomeJSONThroughAjax

我认为这是一个路由问题。简单地摆脱问题的一种可能方法是为上述创建一个模板并将 Action 重命名为executeGetMeSomeJsonThroughAjax(). 但就像我提到的那样,恕我直言,这太过分了,必须有一种更美观、更恰当的方式来完成这项工作。

你们 Symfonians 为进行 Ajax 调用做了什么?

4

2 回答 2

2

即使您没有模板,您仍然需要执行前缀。如果需要,您可以将模板设置为无,或者:

return $this->renderText($jsonEncodeString);

也应该工作。

于 2012-12-10T23:48:17.110 回答
0

这样做的想法是:

控制器:

namespace something;

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\HttpFoundation\Response;

class AjaxController extends Controller {
    public function doSometingInAjaxAction()
    {
        $request        = $this->getRequest();
        $id             = $request->get('id');    
        $em             = $this->getDoctrine()->getManager();
        $object         = $em->getRepository('Bundle:Bundle')->find($id);
        $objectJson     = json_encode($object);        
        return new Response($modelosJson);        
    } }

风景:

<script>
     $(document).ready(function(){

     //...

     $.ajax({
        url: '{{ path('admin_ajax_ajax') }}', 
        data: id,
        success: function (response) 
        {    
         //someting
         }                
     });
     });


</script>

路由器

admin_ajax_ajx:
    path:  /a/supercool/path//
    defaults: { _controller: Bundle:Ajax:doSometingInAjax }

这是我的基础和工作

于 2014-05-19T15:36:57.473 回答