You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何仅使用e.preventDefault()时才能获取Laravel AJAX请求响应?

问题

我只有在调用e.preventDefault()时,才能看到AJAX请求的响应;要是注释掉这个方法,打印请求时响应会是空或者null。

(注:使用e.preventDefault()时,控制台可正常显示响应内容)

HTML代码

<div class="col-lg mt-3">
    <form id="formTUI" action="/designlab" method="POST" enctype="multipart/form-data">
        @csrf
        <div id="outerDiv">
            <div id="tui-image-editor-container" class="col-lg-12 col-md-12" name="image">
            </div>
        </div>
        
        <button type="submit" id="saveImage">Submit</button>
    </form>
</div>

AJAX代码

$('#saveImage').click(function(e){
    e.preventDefault();

    // var image64 = imageEditor.toDataURL();
    var image64 = "Hello World"
    console.log(image64);

    jQuery.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    jQuery.ajax({
        url: '/designlab',
        type: 'POST',
        // processData: false,
        // contentType: false,
        // contentType: 'multipart/form-data',
        data: { image:image64 },
        success: function(response) {
            // Handle the server response
            console.log(response);
        },
        error: function(xhr, status, error) {
            // Handle the error
            console.error(error);
        }
    });
});

Laravel后端代码

public function designPost(Request $request)
{
    try {
        $data = $request->all();
        $image = $request->image;
        return response([$image]);
    } catch (\Exception $e) {
        dump($e->getMessage());
    }
}

补充说明

  • 我没有通过表单提交AJAX请求,而是直接传递payload
  • 尝试过两种获取参数的方式:
$image = $request->image;
// 以及
$image = $request->input('image');

解决办法

这是因为你的按钮是type="submit",点击它会触发浏览器的表单默认提交行为——页面会立刻刷新跳转。

如果不调用e.preventDefault(),AJAX请求刚发出去,页面就被刷新了,AJAX的响应还没来得及返回就被页面刷新覆盖,自然看不到响应内容。

两种解决方式:

  1. 保留e.preventDefault():这个方法会阻止表单的默认提交行为,页面不会刷新,AJAX请求能正常完成并返回响应。
  2. 修改按钮类型:把按钮的type改成button(<button type="button" id="saveImage">Submit</button>),这样按钮就不会触发表单提交,不需要调用e.preventDefault()也能正常执行AJAX。

内容的提问来源于stack exchange,提问作者merchant8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 16:15:07