Laravel Blade-View:处理Api Repsonse [英] Laravel Blade-View: Handling with Api Repsonse

查看:57
本文介绍了Laravel Blade-View:处理Api Repsonse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个简单的刀片视图表单,其中只有一个输入字段和一个提交按钮。在这一栏中,你只需要写一个名字。之后,您需要单击Submit按钮进行API调用。

为简化起见,我们假设API调用是方法:POST和url:‘api/user’

调用API在数据库中创建新用户,并使用json:

进行响应
{
    "id": 1,
    "name": "Im a new user",
    "created_at": 20190119
} 

我知道如果我实现我的blade.view,如下所示:

<form method="POST" action="/api/user">
    @csrf
    <div class="form-group row">
        <label for="username"
               class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>

        <div class="col-md-6">
            <input id="username" type="text"
                   class="form-control"
                   name="username" value="{{ old('username') }}" required autofocus>
        </div>
    </div>
    <div class="form-group row mb-0">
        <div class="col-md-8 offset-md-4">
            <button type="submit" class="btn btn-primary">
                {{ __('Create') }}
            </button>
        </div>
    </div>
</form>

我的页面显示响应。 我想要的是停留在实际视图中,并将响应显示为警报,例如$NAME。‘已创建‘

Api路由(routes/api.php):

Route::post('/user', 'UserController@createUser');

路由配置(routes/web.php):

Route::get('/user' , function () {
return view('user/create-user');
});

我知道可以奏效的解决方案

  • 重定向到同一页(这意味着再次重新呈现同一页,这并不是真正负责-此解决方案导致再次加载整个页面)

  • 在带有数据的UserController@createUser方法中返回相同的视图(与上面相同,据我所知,API调用应该使用json而不是视图进行响应)

我还可以通过JQuery等方式使用AJAX。正如你所看到的,有很多解决方案,但哪一个是最好的。

在这种情况下,您能说有最佳实践吗?

Laravel有没有开箱即用的好解决方案?

推荐答案

我认为您遗漏了一些元素,或者可能希望更多地研究一下各个部分是如何组合在一起的。您的主要请求不是特定的Laravel项目:

我想要的是停留在实际视图中,并将响应显示为警报

问题的关键不是Laravel"开箱即用"的东西,也不是真正的Laravel问题,而是我如何异步更新我的页面。为此,您可能最适合使用AJAX请求,后跟一个javascript/jQuery警报。

我可能会这样做:

$('#submitButton').on('click', function (e) {
        e.preventDefault(); // Want to stay on the page, not go through normal form  
        // Might be easier to make this a NON submit button - then we can use the rest below and not have to js submit()
        // Grab any extra info via data.
        var item_type = $(this).data('item-type');
        var name = $(this).val();
        $.ajax({
            url: "{{url('user/create/')}}",
            type: "POST",
            data: {
                item_type: item_type,
                name: name
            },
            success: function (name) {
                alert(message);
                // Or, if you want a better looking alert, you can use a library like SWAL:
               swal("Success!", "New user created with a name of: "+name, "success");
            },
            error: function () {
                swal("Error", "Unable to bring up the dialog.", "error");
            }
        });
    });

您需要在控制器中处理AJAX数据,并在控制器方法的返回语句中仅发回名称。

如果您想要更改上面的表单而不是通过警报执行此操作,请在Success函数中使用jQuery进行更改(如$("#name").text(name);或类似的内容。

这篇关于Laravel Blade-View:处理Api Repsonse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆