简体   繁体   English

如何在 api 使用 Z686155AF75A60A0F6E9D80C1FZEDD 发布请求后 Laravel 中的 flash 消息?

[英]How to flash message in Laravel after api post request with JavaScript?

Goal目标

Flash a message after a post request is saved successfully to database. Flash post请求成功保存到数据库后的消息。

Problem问题

The message doesn't appear when a post request comes from a react frontend.当发布请求来自反应前端时,该消息不会出现。 If the react frontend receives a success message it reload the page, as you can see in the handleSubmit function.如果反应前端收到成功消息,它会重新加载页面,如您在句柄提交handleSubmit中看到的。 When a request is send from a form generated in the "standard laravel way", everythin works, like expected.当从以“标准 laravel 方式”生成的表单发送请求时,一切正常,如预期的那样。

So here is the code:所以这里是代码:

ReportsController:报告控制器:

use Illuminate\Support\Facades\Session;

...

public function store(Request $request)
  {
    $report = new Report([

      'name' => $request->get('name'),

      'body' => $request->get('body'),

      'visible' => $request->get('visible'),

      'show_in_slider' => $request->get('show_in_slider')

    ]);

    if ($report->save()) {
      Session::flash('success', 'Feedback gespeichert!');
      return response()->json(['success' => true, 'url' => '/admin/reports'], 200);
    }
  }

The line in the api.php api.php中的行

Route::resource("reports", "ReportsController");

The blade for the messages:消息的刀片:

@if(count($errors) > 0)
@foreach($errors->all() as $error)
<div class="warning-modal">
  {{$error}}
</div>
@endforeach
@endif

@if(session("success"))
<div class="alert-modal">
  {{session("success")}}
</div>
@endif

@if(session("error"))
<div class="warning-modal">
  {{session("error")}}
</div>
@endif

The corresponding functions snippets in the React frontend. React 前端中的相应函数片段。

handleSubmit : handleSubmit

async function handleSubmit(event) {
        event.preventDefault();
        const response = await saveData("/api/reports", report);
        if (response.success) {
            window.location = response.url;
        } else {
            alert("Ein Fehler ist aufgetreten.");
        }
    }

Sending the post request in the saveData function:saveData function 中发送 post 请求:

export default async function saveData(api, data) {
    const token = document
        .querySelector('meta[name="csrf-token"]')
        .getAttribute("content");
    const url = window.location.origin + api;
    const response = await fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": token
        },
        body: JSON.stringify(data)
    });

    const result = await response.json();
    return result;
}

So where is the fault?那么错在哪里呢?

Thanks for your time in advance:)提前感谢您的时间:)

Edit编辑

I solved it without reloading the page and let JavaScript handle the alert.我在没有重新加载页面的情况下解决了它,让 JavaScript 处理警报。 Thanks to elyas:)感谢 elyas:)

export default async function PostData() {
    const report = await CollectData();

    const response = await SaveData("/api/reports", report);

    const alert = document.createElement("div");
    alert.innerHTML = response.message;
    if (response.success) {
        alert.className = "alert-modal";
        ToggleNewReport();
    } else {
        alert.className = "warning-modal";
    }

    document.getElementById("content").appendChild(alert);
}

Depending on the response i add the corresponding alert.根据响应,我添加相应的警报。

You are using the javascript async functionality, and your page doesn't reload after send post data.您正在使用 javascript 异步功能,并且您的页面在发送发布数据后不会重新加载。 So you can put your message in json data and show it via javascript.因此,您可以将您的消息放入 json 数据中,并通过 javascript 显示。 in your Controller:在您的 Controller 中:

if ($report->save()) {
  return response()->json(['success' => true, 'url' => '/admin/reports', 'success'=> 'Feedback gespeichert!'], 200);
}

And in JS file:在 JS 文件中:

if (response.success) {
        alert(response.message);
        window.location = response.url;
    } else {
        alert("Ein Fehler ist aufgetreten.");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 ZDB974238714CA8DE634A7CED 使用 JavaScript 向受保护的 Laravel API 路由发出发布请求? - How to make a post request to a protected Laravel API route with JavaScript using the API token? 提交表单发布表单后,如果只能通过发布访问文件,如何将消息发送到html / javascript? 发布请求 - After form post form is submitted, how to send message to html/javascript if file can only be accessed through post? post request CORS 策略阻止 ZA5C95B86291EA299FCZBE64458ED12702 中的 javascript 请求(API 路由上的 POST) - CORS policy block a javascript request (POST on API route) in Laravel Laravel发布请求API不起作用 - Laravel post request api is not working 缺少草稿邮件-JavaScript Gmail API-如何构建请求正文? - Missing draft message - javascript Gmail API - how to structure body of the request? 发布请求后显示消息不起作用 - After post request display message is not working 如何使用 javascript XHR 将表单输入分配给 API 发布请求? - How to assign form inputs to API Post request with javascript XHR? 如何使用库币 API 发出 Javascript POST 请求? - How do I make a Javascript POST request with the KuCoin API? 如何防止页面在 JavaScript 获取帖子请求后刷新? - How to prevent page from refreshing after JavaScript fetch post request? JavaScript Flash消息 - javascript flash message
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM