如何显示对刀片Laravel json响应的验证消息

时间:2020-08-31 02:52:11

标签: javascript php json ajax laravel

我对她感到困惑,我的计划是我想从控制器中的response()->json()获取错误验证消息,并在blade.php中显示该消息,但我无法让他们将它们调用到我的刀片中,但是当我在控制台中检查结果链接时,我的消息验证正在显示它,谁知道我的问题,我将代码放在下面:

我的控制器:

public function testApi(Request $api)
{
   $validator = Validator:make($api->all(), [
      'name_product' => 'required'
   ]);

   if () {
      return response()->json([
         'error' => $validator->messages()
      ], 401);
   } else {
     // my condition if validator is not fail
   }
}

我的刀片:

@if ($errors->any())
   <h4>{{ $error->first() }}</h4>
@endif
@csrf
<div>
    <label>Name Product</label>
    <input type="text" class="form-control" name="name_product" placeholder="Name">
</div>
<div class="form-group">
    <input type="submit" id="productButton" class="btn btn-primary btn-block" value="Add">
</div>

我的js:

document.querySelector('#productButton').addEventListener('click', addProduct);

let urlProduct = '/product/add';
let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

function addProduct() {
   let nameProduct = document.querySelector('input[name="name_product"]').value;

   fetch(urlProduct, {
       headers: {
           "Content-Type": "application/json",
           "Accept": "application/json, text-plain, */*",
           "X-Requested-With": "XMLHttpRequest",
           "X-CSRF-TOKEN": token
      },
      method: 'post',
      credentials: "same-origin",
      body: JSON.stringfy({
          name_product = nameProduct
      })
   }).then((data) => {
      console.log(data);
   }).catch(function (error) {
      console.log(error);
   })
}

谢谢

1 个答案:

答案 0 :(得分:1)

您在提交ajax请求时正在进行post呼叫,并且页面没有刷新,因此

@if ($errors->any())
   <h4>{{ $error->first() }}</h4>
@endif

将不会再次重新呈现。因此,如果您发送blade error请求,那么所有ajax都将无法为您服务。

您可以这样做:

<h4 id="error"></h4>
.then((data) => {
         const h4 = document.getElementById("error");
         h4.innerHTML = data.error;
   })