Laravel - jQuery AJAX 范例

最近满常要把一般 form-submit 改成 AJAX 非同步去送表单,所以分享个 template。
非 Laravel 做的後端也适用

<form id="form">
    <!-- inputs -->
    <button type="submit" id="submit">
        submit
    </button>
</form>
<script>
    $('#submit').click(function(e){
        e.preventDefault();
        var form = new FormData(document.getElementById('form'))
        $.ajax({ 
            url: "/api/endpoint",
            data: form,
            type: 'post',
            processData: false, // important
            contentType: false, // important
            cache: false,
            success: function(data)
            {
                console.log(data)
                // redirect
                window.location.replace(data.redirect);
            },
            error: function(data)
            {
                // intergrate Swal to display error
                Swal.close();
                if (data.status == 419) {
                    window.location.reload();
                } else {
                    Swal.fire({
                        icon: 'info',
                        title: 'Error',
                        html: data.responseJSON.message,
                    });
                }
            }
        });
    })
</script>

Laravel Response 范例

  • json 看前端需要什麽,没有一定规定
  • status code 可参考 HTTP 状态码,建议不要无脑 200
return response()->json([
    'message' => 'message ...',
    'redirect' => 'https://example.com/path'
], 200);

<<:  D30. 学习基础C、C++语言

>>:  30天Python自学:Day02

Day25 在麦块用手持式电脑玩魔术方块

今天来玩 CC: Tweaked Pocket Computer 在工具箱有一排各式各样 Pocke...

过了一个月,有什麽改变?

没想到写一写就满一个月了,对於新创来说,时间真的是一下子就过了,趁铁人赛的机会能够检视自己团队的成长...

[DAY 30] 章节3-10: 晨晓之始-继续统计旅程

3-10 晨晓之始 半夜4:30天还未亮,茉姨便拿着提灯到两人房间叫醒二人,飞哥与小博匆匆起床洗漱後...

D3JsDay27What's the tree?Let me see—树状图(tree diagram)

树状图介绍 以下节录自维基百科树状结构 树状结构(英语:Tree structure),又译树形结构...

Day18-"字串练习-1"

利用两种不同方法分别宣告两字串,并将资料印出,每笔资料都须换行。 . . . . . #inclu...