doupinge9055 2016-11-21 06:56 采纳率: 100%
浏览 39
已采纳

如何使用AJAX POST到Slim框架?

I'm using slim framework with eloquent to talk to the db. I'm trying to make a simple post ajax request that posts the data to db. so I have this route:

//post yell
$app->post('/yell', 'UserController:postYell')->setName('yell');

which is resolved by this controller

public function postYell($request, $response)
{
$yell = Yell::create([
  'body' => $request->getParam('yellBody'),
  'user_id' => $_SESSION['user'],
]);


return $response->withRedirect($_SERVER['HTTP_REFERER']);
}

I tried something like this:

$(".postYell").submit(function(){
    $.ajax(
    {
        url: "/yell",
        type: 'POST',
        data: {
            "_method": 'POST',
        },
        success: function ()
        {
            console.log("it Work");
        }
    });

    console.log("It failed");
});

but I don't think this is the right way to do this. I'm still pretty new to this so pardon me if I'm missing something obvious. I can't find a good example of how to ajax stuff with slim, and I've been stuck on how to do this for a few hours now, so I'd greatly appreciate it if someone could point me in the right direction

  • 写回答

2条回答 默认 最新

  • dqd2800 2016-11-21 07:15
    关注
    // Make sure you specify a valid callable with two ':'
    $app->post('/yell', 'UserController::postYell')->setName('yell');
    

    And then in your controller, don't redirect when it is through XHR:

    public function postYell(Request $request, Response $response) : Response
    {
        $yell = Yell::create([
            'body' => $request->getParam('yellBody'),
            'user_id' => $_SESSION['user']
        ]);
    
        if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
            return $response;
        } else {
            return $response->withRedirect($request->getHeader('Referer'));
        }
    }
    

    Then follow up with the configuration in your AJAX request to send the correct data value (jQuery.ajax automatically adds the X-Requested-With: XMLHttpRequest as documented here under "headers")

    $('form.postYell').submit(function (e) {
        // prevent the page from submitting like normal
        e.preventDefault(); 
    
        $.ajax({
            url: '/yell',
            type: 'POST',
            data: $(this).serialize(),
            success: function () {
                console.log('it worked!');
            },
            error: function () {
                console.log('it failed!');
            }
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退