【问题标题】:How to POST to Slim framework with AJAX?如何使用 AJAX 发布到 Slim 框架?
【发布时间】:2019-05-29 22:16:46
【问题描述】:

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

//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");
});

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

【问题讨论】:

  • 首先您忘记阻止默认提交事件,其次您在 php ajaxed 函数中重定向
  • 您的第二个控制台日志位于提交处理程序的根目录中,这样它总是会记录“失败”

标签: php jquery ajax slim


【解决方案1】:
// 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,如“headers”下记录的here

$('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!');
        }
    });
});

【讨论】:

    【解决方案2】:

    根据 Slim3 文档

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

    是确定请求是否来自 JQuery AJAX 调用的好方法

    投票

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 2014-05-02
      • 1970-01-01
      • 2015-03-13
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多