北城已荒凉 2014-11-02 01:59 采纳率: 0%
浏览 23

带有Symfony的JQuery Ajax

I'm trying to create a game with symfony in which there are warriors. Each warrior has a level. To understand jquery and ajax which i'm new with, i want to create a simple button which when clicked use jquery ajax to get the warrior id and make him lvl up. Here is the level up method controller :

public function warriorLevelUpAction(Warrior $warrior){
    $warrior->levelUp();
    return $this->render('StormbladesWarriorBundle:Warrior:homepage.html.twig', array(
        'warrior' => $warrior
    ));
}

Here is my Jquery ajax method

$('#cpt').click(function() {
    $.ajax({
        url: "/stormblades/web/app_dev.php/warriors/levelUp/"+{{ warrior.id }},
        error: function(xhr, error){
            console.debug(xhr);
            console.debug(error);
        }
    });

And here is my routing :

stormblades_warrior_leveluppage:
path:     /warriors/levelUp/{id}
defaults: { _controller: StormbladesWarriorBundle:Warrior:warriorLevelUp }
requirements:
    id: \d+

Obviously, this doesn't work, i got a beautiful error 500. Any help and suggestion on what's wrong would be appreciate.

  • 写回答

2条回答 默认 最新

  • ℙℕℤℝ 2014-11-02 03:52
    关注

    A couple of things stand out to me.

    Firstly, your warriorLevelUpAction function requires a warrior object, but in the request you are only passing an id. Therefore, you require an extra step to get the warrior by it's ID then level up. For example:

    public function warriorLevelUpAction($id){
        $warrior = $this->getDoctrine()
        ->getRepository('StormbladesWarriorBundle:Warrior')
        ->find($id);
        $warrior->levelUp();
        return $this->render('StormbladesWarriorBundle:Warrior:homepage.html.twig', array(
            'warrior' => $warrior
        ));
    }
    

    Secondly, if you are only ever going to call this function through AJAX, then you could just return a HTTP 200 Status OK, rather then render homepage.html.twig. You don't have to but, I just find it more efficient. Something like this should be fine:

    $response = new Response(Response::HTTP_OK);
    return $response;
    

    Lastly, in your AJAX code, the url should be: "/warriors/levelUp/"+{{ warrior.id }}, unless there is a specific reson you are using the full path. This path will work in both development and production, whereas your current code will always run in Debug Mode.

    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程