如何POST 到AJAX 的Slim 框架?

How to POST to Slim framework with AJAX?

我正在使用带有 eloquent 的 slim 框架与数据库对话。我正在尝试制作一个简单的 post ajax 请求 post 将数据发送到数据库。 所以我有这条路线:

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

由本控制器解析

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


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

我试过这样的事情:

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

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

但我认为这不是正确的方法。我对此还是很陌生,所以如果我遗漏了一些明显的东西,请原谅我。我找不到一个很好的例子来说明如何 ajax 使用 slim,我已经被困在如何做到这一点上几个小时了,所以如果有人能指出我,我将不胜感激正确的方向

// Make sure you specify a valid callable with two ':'
$app->post('/yell', 'UserController::postYell')->setName('yell');

然后在你的控制器中,当它通过 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'));
    }
}

然后跟进您的 AJAX 请求中的配置以发送正确的数据值(jQuery.ajax 自动添加 X-Requested-With: XMLHttpRequest 记录在 here 下 "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!');
        }
    });
});

根据 Slim3 文档

if ($request->isXhr()) {
        return $response;
    }

是确定请求是否来自 JQuery AJAX 调用

的好方法

投赞成票