【问题标题】:How to show a validation message to blade Laravel json response()如何向刀片 Laravel json response() 显示验证消息
【发布时间】:2020-12-19 04:19:58
【问题描述】:

我对她感到困惑,我的计划是我想从控制器中的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);
   })
}

谢谢

【问题讨论】:

  • 未正确使用 fetch() then()。 data 实际上是响应对象,data.json() 是对实际服务器数据的承诺
  • 那我该怎么办?
  • 试试fetch(url, {/* options*/}).then(res=&gt;res.json()).then(data=&gt;console.log(data))
  • 它的工作,之后我只是将我的错误调用到我的刀片中?
  • 进入浏览器开发工具 (F12) 并在网络上深入挖掘实际请求并阅读 html 输出在响应正文中告诉您的内容

标签: javascript php json ajax laravel


【解决方案1】:

您正在拨打ajax 调用,并且页面没有刷新,当您提交post 请求时,这样

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

不会再次重新渲染。因此,如果您发送ajax 请求,所有blade error 都将不适合您。

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2020-02-14
    • 2016-09-12
    • 1970-01-01
    • 2016-10-11
    相关资源
    最近更新 更多