【问题标题】:Jquery and Slimframework - Status RequestJquery 和 Slimframework - 状态请求
【发布时间】:2021-02-21 18:38:51
【问题描述】:

如何使用 Slimframework 3 响应带有多个状态码的 Jquery $.post 调用?

我的代码是:

Javascript:

$.post('/insert/table/' + $pedido, table_data)
     .done(function(data, statusText, xhr) {
         alert(xhr.status);
         if (xhr.status == 201) {
            alert('Done');
         } else {
            alert('Error');
         }
      })
      .fail(function(xhr, textStatus, errorThrown) {
         alert(xhr.responseText);
      });

PHP:

$this->post('/insert/table/{pedido}', 
 \App\Controller\Master\MasterController:SaveTable');

public function SaveTable($request, $response, $args) {
    $params = (object) $request->getParams();
    $logger = $this->container->get('logger');
    $pedido = $args['pedido'];
    if($pedido < 1){
        $logger->error('Arg:Cod Pedido error.');
        $response->withStatus(503);
        return $response;           
    }

    $conn = $this->container->get('DB_Producao');
    if($conn) {
        $tsql= "INSERT INTO .......";
        if(!sqlsrv_query($conn, $tsql)) {
            $logger->error('error');
            $response->withStatus(503);
            return $response;
            die();  
        }
    }
    $response->withStatus(201)
             ->withHeader('Content-Type', 'text/plain')
             ->write('Done');;
    return $response;
}

使用此代码,我总是收到来自发布操作的状态代码 200。我期待的是 201 或 503 状态码。

【问题讨论】:

  • \App\Controller\Master\MasterController:SaveTable' 之前是否缺少引号?如果没有,您可以检查一下您是否收到了Done(使用浏览器上的网络选项卡进行检查)。

标签: javascript php ajax slim


【解决方案1】:

请求和响应标头是“不可变的”。

而不是这个:

$response->withStatus(503);

return $response;

试试这个:

return $response->withStatus(503);

或

$response = $response->withStatus(503);

return $response;
// The headers are immutbale
$response = $response->withStatus(201)
    ->withHeader('Content-Type', 'text/plain');

// The body is not immutable
$response->getBody()->write('Done');

return $response;

【讨论】:

    猜你喜欢
    • 2011-03-10
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    相关资源
    最近更新 更多