【问题标题】:Laravel Ajax response returning text above jsonLaravel Ajax 响应返回 json 上方的文本
【发布时间】:2018-01-22 17:03:43
【问题描述】:

我正在使用 ajax 写入我的模型,如果出现类似重复的错误,我需要它来引发 json 响应。

$model = Product::find($id);
$model->{$col} = $request->value;    

try{
        $model->save();
    } catch (Exception $e){   
        return Response::json(['error' => $e->getMessage()], 500);
    }

如果出现错误,它会返回以下响应代码 200,因此我在 ajax 中的错误处理不会触及这一点。我也无法在成功函数中处理它,因为它不是纯 json

HTTP/1.0 500 Internal Server Error
Cache-Control: no-cache, private
Content-Type:  application/json
Date:          Mon, 22 Jan 2018 16:06:17 GMT

{"error":"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry...."}

我发现在返回之前添加 http_response_code(500) 然后给我一个状态响应 500 但 responseText 仍然相同并且包含额外的文本而不仅仅是纯 json

我想要的回复应该是这样的

{"error":"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry...."}

这是我的 js ajax 代码

var post_data = {id:$(this.attr('id),value:$(this).value()}   



$.ajax({
    type:'POST',
    data: post_data,
    beforeSend:function(){
       //stuff here to show user somethign is happening
    },
    success:function(returned_data){

        console.log('successful!')

        console.log(returned_data);
    },
    error:function(event, jqXHR, ajaxSettings, thrownError ) {
         console.log('event');
         console.log(event);
         console.log('jqXHR');
         console.log(jqXHR.responseText);

         console.log('thrownError');
         console.log(thrownError);
    }

}

laravel 发送的文本看起来像标题,而不仅仅是纯 json,我做错了什么?

编辑:在尝试捕获之前添加代码

另外,我是故意造成这个错误的,所以我可以确保我的错误处理工作正常,但这不是因为我没有得到纯 json 并且它返回 200 响应代码

【问题讨论】:

  • 上面是什么 ----> try{ $model->save();post_data 包含什么?
  • try catchpost data 上面添加了代码。我故意造成错误以检查我的错误处理工作
  • 我不确定这是否有帮助,但您可能想尝试使用这种格式 return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200); 返回数据?
  • 仍然返回json数组上方的文本HTTP/1.0 200 OK Cache-Control: no-cache, private Content-Type: application/json Date: Mon, 22 Jan 2018 18:50:13 GMT {"status":true}

标签: php ajax laravel-5.5


【解决方案1】:

您可能需要检查您的App\Exceptions\Handler

【讨论】:

    【解决方案2】:

    好的,经过大量测试后,我发现了问题。使用我发送回服务器的 ajax 数据,我发送一个函数名,该函数名调用要使用的函数。问题是我使用echo 来推回数据。

    echo $_POST['ajax_function_name']();
    

    echo 更改为return 现在将在使用Response::json(); 时返回正确的json 响应

    发生这种情况的原因是将功能从旧版应用程序转移到新的 laravel 应用程序并忽略了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 2012-07-10
      • 1970-01-01
      • 2014-04-26
      • 2011-05-12
      • 2015-03-29
      相关资源
      最近更新 更多