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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)